其他分享
首页 > 其他分享> > Json

Json

作者:互联网

一.jackson

1.将Object对象转换为Json字符串

先导入jackson的依赖

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
</dependency>

    用jackson中的ObjectMapper

    @Test
    void contextLoads() throws JsonProcessingException {

        //jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("小黄",20,"男");

        String str = mapper.writeValueAsString(user);

        System.out.println(str);
        System.out.println(user.toString());
    }

集合也是一样的

    @Test
    void contextLoads2() throws JsonProcessingException{
        //jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        List<User> userList = new ArrayList<>();
        //创建对象
        User user1 = new User("小黄",20,"男");
        User user2 = new User("小马",25,"女");
        User user3 = new User("小蓝",10,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        String str = mapper.writeValueAsString(userList);

        System.out.println(str);
    }

 

二.fastjson

先导入fastjson的依赖

    <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

 

  @Test
    void fastson1(){
        List<User> userList = new ArrayList<>();
        //创建对象
        User user1 = new User("小黄",20,"男");
        User user2 = new User("小马",25,"女");
        User user3 = new User("小蓝",10,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        //java对象转换为json字符串
        String str1 = JSON.toJSONString(userList);
        System.out.println(str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println(str2);

        //json字符串转换为java对象
        User jp_user = JSON.parseObject(str2,User.class);
        System.out.println(jp_user);

        //java对象转为json对象
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println(jsonObject1);   //获取整个json对象
        System.out.println(jsonObject1.getString("name"));  //获取json对象中某一个值
        
        //Json对象转为java对象
        User to_java_user = JSON.toJavaObject(jsonObject1,User.class);
        System.out.println(to_java_user);
    }

 

标签:System,userList,Json,User,println,new,out
来源: https://www.cnblogs.com/hj98/p/16466556.html