Jackson中json格式的字符串与对象的互相转换方式

2022-11-13 11:11:12 对象 字符串 转换

json格式的字符串与对象的互相转换

Jackson 简介

Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json字符串和xml文档,同样也可以将json、xml转换成Java对象。Jackson所依赖的jar包较少,简单易用并且性能也要相对高些,并且Jackson社区相对比较活跃,更新速度也比较快。

jackson特点

  • 容易使用 - jackson api提供了一个高层次外观,以简化常用的用例。
  • 无需创建映射 - API提供了默认的映射大部分对象序列化。
  • 性能高 - 快速,低内存占用,适合大型对象图表或系统。
  • 干净的JSON - jackson创建一个干净和紧凑的JSON结果,这是让人很容易阅读。
  • 不依赖 - 库不需要任何其他的库,除了jdk
  • 开源代码 - jackson是开源的,可以免费使用。

json格式的字符串与对象的转换

使用Jackson必须要在项目导入对应的jar包。

Book.java文件

package cn.hestyle.bean;
public class Book {
	private String id;
	private String name;
	private double price;
	private int pnum;
	private String cateGory;
	private String description;
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, double price, int pnum, String category, String description) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.pnum = pnum;
		this.category = category;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getPnum() {
		return pnum;
	}
	public void setPnum(int pnum) {
		this.pnum = pnum;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + ", pnum=" + pnum + ", category=" + category
				+ ", description=" + description + "]";
	}
}
package cn.hestyle.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import cn.hestyle.bean.Book;
public class JacksonDemo01 {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		//将对象转换为json格式的字符串
		Book book = new Book("1001", "Java入门到入土", 99.9, 100, "编程开发", "你懂得!");
		String bookJsonStr = objectMapper.writeValueAsString(book);
		System.out.println(bookJsonStr);
		//将集合、数组对象转换为json格式的字符串
		List<Book> bookList = new ArrayList<Book>();
		bookList.add(new Book("1001", "Java入门到入土", 99.9, 100, "编程开发", "你懂得!"));
		bookList.add(new Book("1002", "Python入门到入土", 89.9, 100, "编程开发", "你懂得!"));
		bookList.add(new Book("1003", "c++入门到入土", 89.9, 200, "编程开发", "你懂得!"));
		String bookListJsonStr = objectMapper.writeValueAsString(bookList);
		System.out.println(bookListJsonStr);
		
		//将json格式的字符串转化为对象
		//字符串中含有双引号,需要使用反斜杠转义
		String bookString = "{\"id\":\"1001\",\"name\":\"Java入门到入土\",\"price\":99.9,\"pnum\":100}";
		//Book必须有无参的构造方法
		Book book2 = objectMapper.readValue(bookString, Book.class);
		System.out.println(book2);
	}
}

控制台输出:

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;
}

2.WebSite,站点

@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebSite {
    private String webSiteName;
    private List<User> users;
}

3.User,用户

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String userId;
    private String username;
    private String passWord;
}

json字符串和对象互转

对象转json字符串

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

    
    @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数组字符串


    
    @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数组字符串转数组对象

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

    
    @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方式取值是错的!

正确做法:

    
    @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);
        }
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

相关文章