(二)fastJson和其他类型转换
//String to Json String str = "{\"语文\":\"88\",\"数学\":\"78\",\"计算机\":\"99\"}"; JSONObject jsonObject; jsonObject = JSONObject.parseObject(str); System.out.println("jsonObject: "+jsonObject); // Json to String String chinessName = jsonObject.getString("语文"); System.out.println("chinessName: "+chinessName); //对象转json字符串简单,就一个toJSONString(对象);方法 User user = new User(); user.setName("zhangsan"); user.setPassword("123"); user.setAge(18); String string = JSON.toJSONString(user); System.out.println("user.toString(): "+user.toString()); System.out.println("JSON.toJSONString(user): "+string); System.out.println(".................................................."); //List的json字符串转会list对象,只需要使用parseArray(str,类名.class); User user1 = new User(); user1.setName("lisi"); user1.setPassword("321"); user1.setAge(17); List<User> users = new ArrayList<User>(); users.add(user); users.add(user1); String string2 = JSON.toJSONString(users); System.out.println("user list"+string2); List<User> list = JSON.parseArray(string2, User.class); for (User user2 : list) { System.out.println(user2); } System.out.println(".................................................."); //Map的json字符串转为map对象,使用parseObject(str,new TypeReference<Map<泛型,泛型>>(){}); Map<String,User> map = new HashMap<String,User>(); map.put("用户1", user); map.put("用户2", user1); String string3 = JSON.toJSONString(map); System.out.println(string3);
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25