1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| /** * json字符串转java对象 * 注:字符串中使用双引号需要转义 (" --> \"),这里使用的是单引号 */ @Test public void JsonTOObject(){ /* json字符串转简单java对象 * 字符串:{"password":"123456","username":"dmego"}*/ String jsonStr1 = "{'password':'123456','username':'dmego'}"; User user = JSON.parseObject(jsonStr1, User.class); System.out.println("json字符串转简单java对象:"+user.toString()); /* * json字符串转List<Object>对象 * 字符串:[{"password":"123123","username":"zhangsan"},{"password":"321321","username":"lisi"}] */ String jsonStr2 = "[{'password':'123123','username':'zhangsan'},{'password':'321321','username':'lisi'}]"; List<User> users = JSON.parseArray(jsonStr2, User.class); System.out.println("json字符串转List<Object>对象:"+users.toString()); /*json字符串转复杂java对象 * 字符串:{"name":"userGroup","users":[{"password":"123123","username":"zhangsan"},{"password":"321321","username":"lisi"}]} * */ String jsonStr3 = "{'name':'userGroup','users':[{'password':'123123','username':'zhangsan'},{'password':'321321','username':'lisi'}]}"; UserGroup userGroup = JSON.parseObject(jsonStr3, UserGroup.class); System.out.println("json字符串转复杂java对象:"+userGroup); }
|