FastJson:json字符串与Java对象转换

 FastJson:json字符串与Java对象转换

对象实体类(省略get set toString)

class User {
    String name;
    String age;
    String sex;

    public User(){}

    public User(String name, String age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}

1.1、对象转json字符串

        User user1 = new User("丽丽","24","女");
        String jsonUser = JSONObject.toJSONString(user1);
        System.out.println(jsonUser);//{"age":"24","name":"丽丽","sex":"女"}

 

 1.2、 json字符串转对象

        JSONObject jsonStr = JSONObject.parseObject(jsonUser);
        User user2 = JSONObject.toJavaObject(jsonStr,User.class);


//其他
DataStore<ResidentDTO> residentDTODataStore = JSONObject.parseObject(String.valueOf(jsonStr), new TypeReference<DataStore<ResidentDTO>>() {});

 

2.1、List转json字符串

        List<User> users = new ArrayList<>();
        User userTest1 = new User("李四", "22","男");
        User userTest2 = new User("王五", null,"男");
        users.add(userTest1);
        users.add(userTest2);

        String jsonUsers = JSONObject.toJSONString(users);//[{"age":"22","name":"李四","sex":"男"},{"name":"王五","sex":"男"}]

 

2.2、json字符串转List

        List<User> userlist = JSON.parseArray(jsonUsers,User.class);//[User{name='李四', age='22', sex='男'}, User{name='王五', age='null', sex='男'}]

 

3.1、Map 转json字符串

        Map<String, Object> map = new HashMap();
        map.put("user",user1);
        String mapJson = JSONObject.toJSONString(map);//{"user":{"age":"24","name":"丽丽","sex":"女"}}

 

3.2、json字符串转Map

        JSONObject jsonMap = JSONObject.parseObject(mapJson);
        Map<String, Object> map1 = JSONObject.toJavaObject(jsonMap,Map.class);//{"user":{"sex":"女","name":"丽丽","age":"24"}}

4、FastJson maven依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.75</version>
</dependency>

 

posted @ 2021-06-02 00:57  JacksonLiyq  阅读(1654)  评论(0编辑  收藏  举报