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

Posted JacksonLiyq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);

 

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>

 

以上是关于FastJson:json字符串与Java对象转换的主要内容,如果未能解决你的问题,请参考以下文章

Fastjson 之 Json 对象Json 字符串Java 对象之间的转换

FastJson JSON对象及JavaBean之间的相互转换

[Java安全]fastjson学习

[Java安全]fastjson学习

[Java安全]fastjson学习

FastJson对于JSON格式字符串JSON对象及JavaBean之间的相互转换