本文聚焦Jackson ObjectMapper类————如何序列化java对象为json以及json字符串反序列化为java对象。
首先增加下列依赖:
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'
该依赖会传递增加下面库:
jackson-annotations-2.9.4.jar
jackson-core-2.9.4.jar
jackson-databind-2.9.4.jar
你可以选择合适的版本。
首先我们看基本的读写操作。
ObjectMapper类的readValue API 是简单的入门起点:可以解析或反序列化json内容为java对象。 反之,writeValue API可以序列化任何java对象为json字符串。
我们使用下面Car类带两个字段作为示例,进行序列化或反序列化转换:
public class Car {
private String color;
private String type;
// standard getters setters
}
先看一个简单示例,通过ObjectMapper类的 writeValue()方法序列化java对象至json字符串:
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
输出结果如下:
{"color":"yellow","type":"renault"}
ObjectMapper类的writeValueAsString 和 writeValueAsBytes 方法能够从java对象生成返回json字符串或字节数组:
String carAsString = objectMapper.writeValueAsString(car);
下面是一个简单的json字符串,我们使用ObjectMapper类转成java对象:
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class);
readValue方法也可以接收其他格式输入,如包含json串的文件:
Car car = objectMapper.readValue(new File("target/json_car.json"), Car.class);
或者是url:
Car car = objectMapper.readValue(new URL("target/json_car.json"), Car.class);
另外,也可以解析json为JsonNode对象,用于获取特定节点的值:
String json = "{ \"color\" : \"Black\", \"type\" : \"FIAT\" }";
JsonNode jsonNode = objectMapper.readTree(json);
String color = jsonNode.get("color").asText();
// Output: color -> Black
json数组可以被解析为java list对象:
String jsonCarArray =
"[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
List listCar = objectMapper.readValue(jsonCarArray, new TypeReference>(){});
json字符串可以被解析为java Map:
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Map map
= objectMapper.readValue(json, new TypeReference
jackson库最强大功能说高度定置化的序列化和反序列过程。本节我们看看这些高级特性生成的输入或输出json与默认生成的json的差异。
当转换json为java对象时,如何json传有多余的字段,那么缺省过程会抛异常:
String jsonString
= "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
在缺省过程下,上面json字符串解析为Car类型对象过程中将抛出UnrecognizedPropertyException异常。通过configure方法可以配置忽略新字段:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Car car = objectMapper.readValue(jsonString, Car.class);
JsonNode jsonNodeRoot = objectMapper.readTree(jsonString);
JsonNode jsonNodeYear = jsonNodeRoot.get("year");
String year = jsonNodeYear.asText();
另外一个选项是FAIL_ON_NULL_FOR_PRIMITIVES,原始类型值可以为null:
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
类似的,FAIL_ON_NUMBERS_FOR_ENUM控制枚举值在序列化/反序列化过程允许作为数值:
objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false);
完整序列化/反序列化特性列表参考官方文档。
ObjectMapper类另一个重要特性是能够注册自定义序列化或反序列化转换。对应输入或输出json响应与java 类结构不同的场景下非常有用。
下面示例自定义序列化转换器:
public class CustomCarSerializer extends StdSerializer {
public CustomCarSerializer() {
this(null);
}
public CustomCarSerializer(Class t) {
super(t);
}
@Override
public void serialize(Car car, JsonGenerator jsonGenerator, SerializerProvider serializer) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("car_brand", car.getType());
jsonGenerator.writeEndObject();
}
}
自定义序列化转换器执行:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module =
new SimpleModule("CustomCarSerializer", new Version(1, 0, 0, null, null, null));
module.addSerializer(Car.class, new CustomCarSerializer());
mapper.registerModule(module);
Car car = new Car("yellow", "renault");
String carJson = mapper.writeValueAsString(car);
输出json字符串如下:
var carJson = {"car_brand":"renault"}
下面定义一个json反序列化转换器:
public class CustomCarDeserializer extends StdDeserializer {
public CustomCarDeserializer() {
this(null);
}
public CustomCarDeserializer(Class> vc) {
super(vc);
}
@Override
public Car deserialize(JsonParser parser, DeserializationContext deserializer) {
Car car = new Car();
ObjectCodec codec = parser.getCodec();
JsonNode node = codec.readTree(parser);
// try catch block
JsonNode colorNode = node.get("color");
String color = colorNode.asText();
car.setColor(color);
return car;
}
}
自定义反序列化转换器执行:
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module =
new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
module.addDeserializer(Car.class, new CustomCarDeserializer());
mapper.registerModule(module);
Car car = mapper.readValue(json, Car.class);
缺省java.util.Date序列化生成数值表示的 epoch timestamp(从1970 1月1号 utc 到现在的毫秒数)。但这不是人类可读格式,需要序列化为人类可读模式。下面封装前面使用的Car类实例至Request类中,并增加datePurchased属性:
public class Request
{
private Car car;
private Date datePurchased;
// standard getters setters
}
我们转换日期格式为:yyyy-MM-dd HH:mm,代码如下:
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
objectMapper.setDateFormat(df);
String carAsString = objectMapper.writeValueAsString(request);
// output: {"car":{"color":"yellow","type":"renault"},"datePurchased":"2016-07-03 11:43 AM CEST"}
另外还有一个有用反序列化的小特性是从json字符串数组生成java集合类型,如数组:
String jsonCarArray =
"[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class);
// print cars
或List:
String jsonCarArray =
"[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
ObjectMapper objectMapper = new ObjectMapper();
List listCar = objectMapper.readValue(jsonCarArray, new TypeReference>(){});
// print cars
Jackson ObjectMapper是强大、成熟的JSON序列化/反序列化库。其API提供了一个简单、灵活方法解析和生成JSON。