常用的json对象转换

时间:2025-02-16 08:19:18

因经常使用,用到又比较容易忘记,特此进行总结。有遇到新的会进行更新。

1.实体类或集合转JSON字符串

import ;
//alibaba fastjson
 String jsonString = (entity);

import ;
//hutool
String jsonString = (list);

字符串转JSONObject

        String jsonString="{\"id\":\"1\",\"name\":\"lyy\"}";
         //fastjson
        JSONObject jsonObject = (jsonString);
         responseJSON = (jsonString);

字符串转实体类

//fastjson
实体类 javaBean = (json, 实体类.class);
//hutool
实体类 javaBean = (json, 实体类.class);

转list对象

 responseJSON = (jsonString);
        List<RoleVO> upperRoles = (("roles"), );

5.将多个jsonObject合成一个jsonObject(fastjson)。

JSONObject jsonThree = new JSONObject();
        (jsonOne);
        (jsonTwo);

转实体类(fastjson)。

LinkedHashMap<String,Object> hashMap = new LinkedHashMap<>();
("name", "张三");
("age", 20);
("addr", "湖北武汉1号");
User user = ((hashMap), );

主要是fastjson和hutool工具类的方法。