因经常使用,用到又比较容易忘记,特此进行总结。有遇到新的会进行更新。
1.实体类或集合转JSON字符串
import com.alibaba.fastjson.JSONObject;
//alibaba fastjson
String jsonString = JSONObject.toJSONString(entity);
import cn.hutool.json.JSONUtil;
//hutool
String jsonString = JSONUtil.toJsonStr(list);
2.JSON字符串转JSONObject
String jsonString="{\"id\":\"1\",\"name\":\"lyy\"}";
//fastjson
JSONObject jsonObject = JSONObject.parseObject(jsonString);
cn.hutool.json.JSONObject responseJSON = JSONUtil.parseObj(jsonString);
3.JSON字符串转实体类
//fastjson
实体类 javaBean = JSON.parseObject(json, 实体类.class);
//hutool
实体类 javaBean = JSONUtil.toBean(json, 实体类.class);
4.JSONArray转list对象
cn.hutool.json.JSONObject responseJSON = JSONUtil.parseObj(jsonString);
List<RoleVO> upperRoles = JSONUtil.toList(responseJSON.getJSONArray("roles"), RoleVO.class);
5.将多个jsonObject合成一个jsonObject(fastjson)。
JSONObject jsonThree = new JSONObject();
jsonThree.putAll(jsonOne);
jsonThree.putAll(jsonTwo);
6.LinkedHashMap转实体类(fastjson)。
LinkedHashMap<String,Object> hashMap = new LinkedHashMap<>();
hashMap.put("name", "张三");
hashMap.put("age", 20);
hashMap.put("addr", "湖北武汉1号");
User user = JSON.parseObject(JSON.toJSONString(hashMap), User.class);
主要是fastjson和hutool工具类的方法。