Jackson简介
Jackson是一个简单的、功能强大的、基于Java的应用库。它可以实现Java对象和Json对象/XML文档之间的互转。它也是spring家族默认的JSON/XML解析器。
相关网站链接:
pom中的依赖如下,
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${
jackson.core.version}</version>
</dependency>
TypeReference
TypeReference是jackson的核心成员,它能够支持对泛型对象的反序列化。
package com.hust.zhang.generic;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TypeReferenceDemo {
private static final ObjectMapper objectMapper = new ObjectMapper();
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
private static class Demo {
private String name;
private int age;
}
public static void main(String[] args) {
// 泛型的反序列化
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
List<String> stringList = getResponse(JSON.toJSONString(list), null, new TypeReference<List<String>>() {
});
String test = "{\"age\":1,\"name\":\"zhangsan\"}";
Demo testObj1 = getResponse(test, Demo.class, null);
Demo testObj2 = getResponse(test, null, new TypeReference<Demo>() {
});
System.out.println(stringList);
System.out.println(JSON.toJSONString(testObj1));
System.out.println(JSON.toJSONString(testObj2));
}
private static <T> T getResponse(String request, Class<T> clazz, TypeReference<T> typeReference) {
T result;
if (clazz != null) {
result = unMarshal(request, clazz);
} else {
result = unMarshal(request, typeReference);
}
return result;
}
private static <T> T unMarshal(String request, Class<T> clazz) {
try {
return objectMapper.readValue(request, clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
private static <T> T unMarshal(String request, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(request, typeReference);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
以上面示例为例,列表可以通过TypeReference传入泛型对象进行反序列化。