springmvc中json转换工具的使用总结

JacksonJson是SpringMVC内置的json处理工具,其中有一个ObjectMapper`类,可以方便的实现对json的处理。

注入ObjectMapper对象

@Autowired
    ObjectMapper objectMapper;

1.将对象 转换为 json:
(使用objectMapper对象的writeValueAsString方法)

@Test
    void testObject2json() throws Exception{
    
    
        HashMap<String, User> map = new HashMap<>();
        map.put("laowang", new User(1, "pig", "gz sss", 1, new Date()));
        map.put("laowang", new User(2, "mouse", "gz sss", 1, new Date()));

        // 对象转json
        String json = objectMapper.writeValueAsString(map);
        System.out.println("json is " + json);
    }

在这里插入图片描述

2.将json 转换为 普通对象:
(使用objectMapper对象的readValue方法)

@Test
    void testjson2Object() throws Exception{
    
    
        // json 串
        String json = "{\"id\":2,\"username\":\"mouse\",\"address\":\"gz sss\",\"sex\":1,\"birthday\":1608776995039}";

        User user = objectMapper.readValue(json, User.class);
        System.out.println(user);
    }

在这里插入图片描述

3.将列表 json 转换为 列表对象:
(使用objectMapper对象的readValue方法。)readValue(json,objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class)

void testJson2ListObject() throws Exception {
    
    
        // 1.准备一个 json 的串
        ArrayList<User> list = new ArrayList<>();
        Collections.addAll(list,
                new User(1, "pig", "gz sss", 1, new Date()),
                new User(2, "dog", "sg sss", 1, new Date())
        );
        String json = objectMapper.writeValueAsString(list);
        System.out.println("json is " + json);

        // 2.将 列表 json 串 转换为  列表 User 对象
        List<User> users = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class));

        for (User u : users) {
    
    
            System.out.println(u);
        }
    }

在这里插入图片描述

4.将 任意对象结构的json串 转换为 对应对象(此处转换为map对象):
(使用objectMapper对象的readValue方法。)
readValue(json, new TypeReference<Map<String, User>>() {})

@Test
    void testConvert() throws Exception{
    
    
        // json 串
        String json = "{\"laowang\":{\"id\":2,\"username\":\"mouse\",\"address\":\"gz sss\",\"sex\":1,\"birthday\":1608777260906}}";

        Map<String, User> map = objectMapper.readValue(json, new TypeReference<Map<String, User>>() {
    
    });
        System.out.println(map);
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hambur_/article/details/111610217