使用Jackson进行json转对象,对象转json总结

背景

在前后端分离的项目中,后端经常涉及到json与对象互转的场景。阿里巴巴的Fastjson是好用,但是,因为技术领导的原因(可能因为fastjson1的各种问题很多吧),不让用,所以就需要选择其他技术栈。当前比较常用的是SpringBoot自带的Jackson或者谷歌的Gson。
下面,做一下使用Jackson的总结。

JavaBean准备

  1. Company,公司
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Company {
    private String companyName;
    private List<WebSite> webSites;
}
  1. WebSite,站点
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebSite {

    private String webSiteName;
    private List<User> users;

}
  1. User,用户
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String userId;
    private String username;
    private String password;
}

json字符串和对象互转

对象转json字符串

不管你是什么结构的对象,想转json,直接objectMapper.writeValueAsString()搞定。

    /**
     * 序列化:对象转json字符串,包含多个数组
     *
     */
    @Test
    public void testObject2Json2() {
        User user2 = new User("1","上海辟谣专属队","职业辟谣,不信谣,不传谣,呵呵");
        List<User> users = new ArrayList<>();
        users.add(user2);
        WebSite webSite = new WebSite();
        webSite.setWebSiteName("xxxxxx.com");
        webSite.setUsers(users);

        List<WebSite> webSites = new ArrayList<>();
        webSites.add(webSite);
        Company company = new Company();
        company.setCompanyName("yyyyyy");
        company.setWebSites(webSites);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(company);
            System.out.println(jsonString);
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }

    }

输出:

{"companyName":"yyyyyy","webSites":[{"webSiteName":"xxxxxx.com","users":[{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}]}]}

json字符串转对象

注意:这种情形是json对象字符串,不能是json数组字符串,后面会说到。

    @Test
    public void testJson2Object() {

        String json = "{\"companyName\":\"yyyyyy\",\"webSites\":[" +
                "{\"webSiteName\":\"xxxxxx.com\",\"users\":[{\"userId\":\"1\",\"username\":\"上海辟谣专属队\",\"password\":\"职业辟谣,不信谣,不传谣,呵呵\"}]}" +
                "]}";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Company company = objectMapper.readValue(json, Company.class);
            System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername());
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

输出:

上海辟谣专属队

json数组字符串和数组(集合)对象互转

有个大坑

数组对象转json数组字符串


    /**
     * 序列化:数组对象转json数组类型的字符串
     *
     */
    @Test
    public void testObjectArray2JsonArrayString() {
        User user1 = new User("1","上海带刀沪卫","带刀大佬");
        User user2 = new User("1","上海辟谣专属队","职业辟谣,不信谣,不传谣,呵呵");
        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(users);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

输出:

[{"userId":"1","username":"上海带刀沪卫","password":"带刀大佬"},{"userId":"1","username":"上海辟谣专属队","password":"职业辟谣,不信谣,不传谣,呵呵"}]

json数组字符串转数组对象

先演示一下错误的写法先演示一下错误的写法先演示一下错误的写法,重要的事情说三遍!

    /**
     * 反序列化:数组类型的json字符串转对象数组
     *
     */
    @Test
    public void testJsonArrayString2ObjectArray() {
        String json = "[" +
                "{\"userId\":\"1\",\"username\":\"上海带刀沪卫\",\"password\":\"带刀大佬\"}" +
                ",{\"userId\":\"1\",\"username\":\"上海辟谣专属队\",\"password\":\"职业辟谣,不信谣,不传谣,呵呵\"}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
			//错误写法
            List<User> list = objectMapper.readValue(json, List.class);
            list.forEach(user -> {
                System.out.println(user.getUsername());
            });

        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }

    }

输出异常


java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xywei.springboot.springtestdemo.entity.User

	at java.util.ArrayList.forEach(ArrayList.java:1259)
	at com.xywei.springboot.springtestdemo.junit.TestUseJackson.testJsonArrayString2ObjectArray(TestUseJackson.java:160)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at 

#省略大段……
Process finished with exit code -1

因为实际转成了map类型,所以使用List方式取值是错的!使用Jackson进行json转对象,对象转json总结_第1张图片
正确做法:

    /**
     * 反序列化:数组类型的json字符串转对象数组
     *
     */
    @Test
    public void testJsonArrayString2ObjectArray() {
        String json = "[" +
                "{\"userId\":\"1\",\"username\":\"上海带刀沪卫\",\"password\":\"带刀大佬\"}" +
                ",{\"userId\":\"1\",\"username\":\"上海辟谣专属队\",\"password\":\"职业辟谣,不信谣,不传谣,呵呵\"}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            TypeReference<List<User>> typeReference = new TypeReference<List<User>>() {
            };
            List<User> list = objectMapper.readValue(json, typeReference);
            list.forEach(user -> {
                System.out.println(user.getUsername());
            });

        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }

    }

最终输出:

上海带刀沪卫
上海辟谣专属队

同时,对多层嵌套的数组也适用:

    @Test
    public void testJsonArrayString2ObjectArray2() {
        String json = "[" +
                    "{" +
                    "\"companyName\":\"yyyyyy\",\"webSites\":[" +
                            "{\"webSiteName\":\"xxxxxx.com\",\"users\":[" +
                                "{\"userId\":\"1\",\"username\":\"上海辟谣专属队\",\"password\":\"职业辟谣,不信谣,不传谣,呵呵\"}" +
                                "]" +
                            "}" +
                        "]" +
                    "}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            TypeReference<List<Company>> typeReference = new TypeReference<List<Company>>() {
            };
            List<Company> list = objectMapper.readValue(json, typeReference);
            list.forEach(company -> {
                System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername());
            });

        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

总结

以上是在项目中常用的,当然还有一些小弟没有用过的,希望各位大佬分享一下!

你可能感兴趣的:(Java,json,java,开发语言)