Jackson 快速入门示例
以下是使用 Jackson 进行 JSON 处理的快速入门示例。这些示例显示了 Jackson 的
ObjectMapper
类的基本数据绑定功能。
Maven dependency
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
简单的Java对象转换
Java Object 转 JSON:
Map<String, Integer> map = Map.of("one", 1, "two", 2);
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(map);
System.out.println(s);
{"one":1,"two":2}
JSON 转 Java Object:
String jsonString = "{\"bananas\":2,\"apple\":5}";
ObjectMapper om = new ObjectMapper();
Map map = om.readValue(jsonString, Map.class);
System.out.println(map);
System.out.println(map.getClass());
{bananas=2, apple=5}
class java.util.LinkedHashMap
POJO 转换
public class MyObject {
private int intVal;
private String StringVal;
private List<String> list;
......
}
POJO 转 JSON
MyObject pojo = new MyObject();
pojo.setIntVal(3);
pojo.setStringVal("test string");
pojo.setList(List.of("item1", "item2"));
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(pojo);
System.out.println(s);
{"intVal":3,"list":["item1","item2"],"stringVal":"test string"}
JSON 转 POJO
String s = "{\"list\":[\"item3\",\"item4\"],\"stringVal\":\"test string2\",\"intVal\":5}";
ObjectMapper om = new ObjectMapper();
MyObject obj = om.readValue(s, MyObject.class);
System.out.println(obj);
MyObject{intVal=5, StringVal='test string2', list=[item3, item4]}
带泛型的转换
泛型 List 转 Json
MyObject pojo = new MyObject();
pojo.setIntVal(3);
pojo.setStringVal("test string");
pojo.setList(List.of("item1", "item2"));
List<MyObject> list = List.of(pojo);
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(list);
System.out.println(s);
[{"intVal":3,"list":["item1","item2"],"stringVal":"test string"}]
Json 转泛型 POJO
String s = "[{\"intVal\":3,\"list\":[\"item1\",\"item2\"],\"stringVal\":\"test string\"}]";
ObjectMapper om = new ObjectMapper();
List<MyObject> list = om.readValue(s, List.class);
System.out.println(list.get(0));
System.out.println(list.get(0).getClass());
{intVal=3, list=[item1, item2], stringVal=test string}
Exception in thread "main" java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class org.example.c1.MyObject (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; org.example.c1.MyObject is in unnamed module of loader 'app')
at org.example.c1.PojoTypeReference.toPojo(PojoTypeReference.java:41)
at org.example.c1.PojoTypeReference.main(PojoTypeReference.java:20)
以上方式会抛出异常 java.lang.ClassCastException
,因为 Jackson 无法推断实际的类型,会返回一个 List<LinkedHashMap>
,而不是 List<MyObject>
。可以通过 TypeReference
的匿名实例来解决这个问题:
String s = "[{\"intVal\":3,\"list\":[\"item1\",\"item2\"],\"stringVal\":\"test string\"}]";
ObjectMapper om = new ObjectMapper();
List<MyObject> list = om.readValue(s, new TypeReference<List<MyObject>>() { });
System.out.println(list.get(0));
System.out.println(list.get(0).getClass());
MyObject{intVal=3, StringVal='test string', list=[item1, item2]}
class org.example.c1.MyObject
读写文件
MyObject myObject = new MyObject();
myObject.setIntVal(3);
myObject.setStringVal("test string");
myObject.setList(List.of("item1", "item2"));
// 创建临时文件
File tempFile = File.createTempFile("jackson-", ".txt");
System.out.println("-- saving to file --");
System.out.println(tempFile);
// 将 myObject 以 JSON 的形式写入文件
ObjectMapper om = new ObjectMapper();
om.writeValue(tempFile, myObject);
// 直接读文件
System.out.println("-- reading as text from file --");
String s = new String(Files.readAllBytes(tempFile.toPath()));
System.out.println(s);
// 从文件中读取 JSON,并反序列化为 MyObject 对象
System.out.println("-- reading as Object from file --");
MyObject myObject2 = om.readValue(tempFile, MyObject.class);
System.out.println(myObject2);
-- saving to file --
C:\Users\zhaobs\AppData\Local\Temp\jackson-2255001324025141241.txt
-- reading as text from file --
{"intVal":3,"list":["item1","item2"],"stringVal":"test string"}
-- reading as Object from file --
MyObject{intVal=3, StringVal='test string', list=[item1, item2]}
通过 URL 读取
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
ObjectMapper om = new ObjectMapper();
Object o = om.readValue(url, Object.class);
System.out.println(o);
System.out.println("Read as: "+o.getClass().getName());
{userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto}
Read as: java.util.LinkedHashMap