其他分享
首页 > 其他分享> > 简单学习一下Jackson

简单学习一下Jackson

作者:互联网

Jackson可以轻松的将Java对象转换成为json对象和xml对象,同样也可以将json,xml转换成Java对象。不仅限于对Java对象,对于Map,List,Array同样有效。

将对象转化成字节数组

public byte[] writeValueAsBytes(Object value)

将字节数组转换成简单对象

public <T> T readValue(byte[] src, Class<T> valueType)

将对象转化成json

public String writeValueAsString(Object value)

将json字符串转换成对象

public <T> T readValue(String content, Class<T> valueType)

maven中添加Jackson的相关依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
 </dependency>

简单的Json和JavaBean,简单的数据类型之间的转换

//JavaBean/Map/List/Array
public static void main(String[] args) {
	ObjectMapper objectMapper = new ObjectMapper();
	User user = new User();
	user.setId(1);
	user.setName("whw");
	
	List<String> list = new ArrayList<>();
	list.add("A");
	list.add("B");
	list.add("C");
	
	Map<String, Object> map = new HashMap<String, Object>();
    map.put("a", "1");
    map.put("b", "2");
    map.put("c", "3");
    map.put("list", list);
    
	try {
        System.out.println(objectMapper.writeValueAsString(user));
        System.out.println(objectMapper.writeValueAsString(list));
        System.out.println(objectMapper.writeValueAsString(map));
        System.out.println(objectMapper.writeValueAsString(sz));

		User a = objectMapper.readValue(s, User.class);
        System.out.println(a.getName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

输出打印:
{"id":1,"name":"whw"}
["a","b","c"]
{"b":"2","c":"3","a":"1","list":["a","b","c"]}
["a","b","c"]
whw

字节数组转换成复杂的列表对象
对于简单的对象来说可以直接使用其类的限定名,如java.lang.String等

对于复杂的列表对象来说,例如:java.utils.Map<java.lang.String, java.util.List>,这类需要使用:
getTypeFactory().constructFromCanonical(type)转化成JavaType再进行类型转化;

/**
  * 将字节数组转换成对象
  * 对于简单对象来说type就是其类的全限定名,如java.lang.String;
  * 对于复杂列表对象来说,type例子:java.util.Map<java.lang.String, java.util.List<test.Person>>
*/
public static Object byteToObject(byte[] bytes, String type) {
    JavaType javaType = MAPPER.getTypeFactory().constructFromCanonical(type);
    try {
        Object object = MAPPER.readValue(bytes, javaType);
        return object;
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("bytesToObject error");
    }
    return null;
}

标签:map,Jackson,String,对象,list,学习,简单,public,objectMapper
来源: https://blog.csdn.net/whw2225404841/article/details/121145690