-
JSON类型的String转成List
List<String> list=JSON.parseArray((String) x,String.class);
-
对象和字符串之间的互转
将对象转换成字符串 String str=JSON.toJSONString(infoDto); 字符串转换成对象 InfoDto infoDto=JSON.parseObject(str,InfoDto.class);
-
对象集合与字符串之间的互转
将对象集合转换成字符串 String users=Json.toJSONString(users); 将字符串转换成对象集合 List<User> userList=JSON.parseArray(userStr,User,class);
-
字符串互转JSONObject
String转Json对象 JSONObject jsonObject=JSONObject.parseObject(jsonString); json对象转String String jsonString=jsonObject.toJSONString();
-
字符串和Map之间互转
字符串转map JSONObject jsonObject=JSONObject.parseObject(str); Map<String,Object> map=(Map<String,Object>)jsonObject; map转字符串 String jsonString=JSON.toString(map);
-
Map转Json对象
map转json对象 Map<string,Object> map=new HashMap(); map.put(“age”,"25"); JSONObject json=new JSONObject(map); json对象转Map Map<String,Object> map=(Map<String,Object>) jsonObject;
-
JSON数组形式字符串转换成List<Map<String,String >>
List<Map<String,String>> list=(List,Map<String,String>) JSONArray.parse(strArr); List<Map<String,String>> list=JSONArray.parseObject(strArr,List.class);
总结:
速记小技巧
- 一切对象转json字符串(json序列化)都可以调用JSON.toJSONString(),除了JSONObject,他需要使用JSONObject.toJSONString()
- 所有JSON字符串转List,都可以使用基础的JSON.parseArray(str,(List的泛型的).class)
- 所有的JSON都是大写
- Map和JSONObject可以强转
- JSON转非数组对象都可以使用JSON.parseObject(str,对象.class),除了JSONObject,他需要使用JSONObject.parseObject(str)
参考:
https://blog.csdn.net/weixin_30729609/article/details/95026537
https://www.cnblogs.com/chancy/p/10179151.html
https://www.cnblogs.com/heqiyoujing/p/9840424.html