Jackson ObjectMapper对象
使用ObjectMapper进行读写
我们可以使用ObjectMapper的readValue方法将JSON内容反序列化为Java对象。同样,我们也可以使用wrtieValue方法将Java对象序列化为JSON。
public class Car {
private String name;
private Integer age;
// standard getters setters
}
Java对象转JSON
File file = new File("user.json");
ObjectMapper mapper = new ObjectMapper();
User user = new User("张三", 20);
mapper.writeValue(file, user);
// 文件中输出
// {"name":"张三","age": 20}
如果希望将Java对象转换为字符串或者字节数组,可以使用writeValueAsString
和writeValueAsBytes
方法:
String userAsString = mapper.writeValueAsString(user);
JSON转Java对象
String userString = "{\"name\":\"张三\",\"age\":20}";
User user = mapper.readValue(bodyString, User.class);
readValue
函数还可以接受其它形式的输入,比如从JSON文件中读取数据:
File file = new File("/SpringMVC/SpringMvcDemo-01/user.json");
User user = mapper.readValue(file, User.class);
或者从网络获取JSON字符串文件:
URL url = new URL("https://raw.githubusercontent.com/SpringMVC/master/SpringMvcDemo-01/user.json");
User user = mapper.readValue(url, User.class);
System.out.println(user);
日期处理
Data转long
默认的Jackson
日期格式,该格式将 Date 序列化为来自1970年1月1日以来的毫秒数(long类型)。
使用SimpleDateFormat
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = dateFormat.format(date);
使用ObjectMapper内置的时间处理
// 不使用时间戳方式
mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
// 设置日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(dateFormat);
Date date = new Date();
String str = mapper.writeValueAsString(date);
集合处理
String usersString = "[{\"name\":\"张三\",\"age\":20},{\"name\":\"李四\",\"age\":21}]";
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
User[] users = mapper.readValue(usersString, User[].class);
或者List
:
String usersString = "[{\"name\":\"张三\",\"age\":20},{\"name\":\"李四\",\"age\":21}]";
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
List<User> users = mapper.readValue(usersString, new TypeReference<List<User>>() {});
忽略未知的JSON字段
有时候,JSON 中的字段要比 Java 对象的字段多的情况下,Jackson
会在这种情况下抛出异常,因为在 Java 对象中找不到该字段。这种情况下可以使用Jackson
配置忽略这些额外的字段。
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
不允许基本类型为null
如果 JSON 字符串包含其值为null
的字段对应相应的Java对象中是基本数据类型的字段,Jackson ObjectMapper默认会处理基本数据类型为null的情况,我们可以将Jackson ObjectMapper默认配置为失效,这样基本数据为null就会转换失败。
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);
Jackson JSON 树模型
String usersString = "[{\"name\":\"张三\",\"age\":20},{\"name\":\"李四\",\"age\":21}]";
JsonNode jsonNode = mapper.readTree(usersString);
System.out.println(jsonNode);
嵌套JSON对象
假设我们有如下JSON数据源。
{
"id": "957c43f2-fa2e-42f9-bf75-6e3d5bb6960a",
"name": "手机",
"brand": {
"id": "9bcd817d-0141-42e6-8f04-e5aaab0980b6",
"name": "华为",
"owner": {
"id": "b21a80b1-0c09-4be3-9ebd-ea3653511c13",
"name": "华为技术有限公司"
}
}
}
现在我们需要将上述嵌套的JSON数据序列化到Product对象中,分别将JSON字符串中的第一个、第二个、第三个name映射到Product的name、brandName、ownerName字段上。
package com.example.springmvcdemo01.dao;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Map;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private String id;
private String name;
private String brandName;
private String ownerName;
@JsonProperty("brand")
public void unpackNested(Map<String, Object> brand) {
this.brandName = (String) brand.get("name");
Map<String, String> owner = (Map<String, String>) brand.get("owner");
this.ownerName = owner.get("name");
}
}
要映射嵌套的brandName属性,首先需要将嵌套的brand对象解析道Map中并获取name属性,然后映射到ownerName,需要将嵌套的owner对象解析道Map中并获取name属性。
File file = new File("/Users/liangzhiwei/同步空间/SpringMVC/SpringMvcDemo-01/user.json");
Product product = mapper.readerFor(Product.class).readValue(file);
System.out.println(product);
使用JsonNode映射
首先,使用ObjectMapper对象的readTree方法将JSON字符串转换为JsonNode对象,然后从JsonNode对象中功能获取所需的值。
File file = new File("/Users/liangzhiwei/同步空间/SpringMVC/SpringMvcDemo-01/user.json");
JsonNode jsonNode = mapper.readTree(file);
String id = jsonNode.get("id").textValue();
String name = jsonNode.get("name").textValue();
String brand = jsonNode.get("brand").get("name").textValue();
String ownerName = jsonNode.get("brand").get("owner").get("name").textValue();
Product product = new Product(id, name, brand, ownerName);
System.out.println(product);
最后更新于
这有帮助吗?