1.概述
Jackjson如何处理具有未知属性的JSON内容。
2.使用其他/未知字段解组JSON
JSON输入内容化-在大多数情况下,需要将其映射到具有一定数量字段的预定义Java对象。 目标是简单地忽略所有无法映射到现有Java字段的JSON属性。
@Data
public class MyDtoGlobalField {
private String stringValue;
private int intValue;
private boolean booleanValue;
}
2.1 未知字段上的UnrecognizedPropertyException
@Test
public void test24()
throws IOException {
String jsonAsString ="{\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"lisi\",\"stringValue2\":\"lisi2\"}";
ObjectMapper mapper = new ObjectMapper();
MyDtoGlobalField readValue = mapper.readValue(jsonAsString, MyDtoGlobalField.class);
System.out.println(readValue);
}
输出
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "stringValue2" (class com.example.demo.pojo.MyDtoGlobalField), not marked as ignorable (3 known properties: "stringValue", "booleanValue", "intValue"])
at [Source: (String)"{"intValue":0,"booleanValue":false,"stringValue":"lisi","stringValue2":"lisi2"}"; line: 1, column: 73] (through reference chain: com.example.demo.pojo.MyDtoGlobalField["stringValue2"])
2.2使用ObjectMapper处理未知字段
可以配置完整的ObjectMapper来忽略JSON中的未知属性:
new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
@Test
public void test25() throws IOException {
String jsonAsString = "{\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"lisi\",\"stringValue2\":\"lisi2\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyDtoGlobalField readValue = mapper.readValue(jsonAsString, MyDtoGlobalField.class);
System.out.println(readValue);//MyDtoGlobalField(stringValue=lisi, intValue=0, booleanValue=false)
}
2.3在类上处理未知字段
还可以将单个类标记为接受未知字段,而不是整个Jackson对象映射器:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDtoIgnoreUnknown {
private String stringValue;
private int intValue;
private boolean booleanValue;
}
@Test
public void test26() throws IOException {
String jsonAsString = "{\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"lisi\",\"stringValue2\":\"lisi2\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
System.out.println(readValue);//MyDtoGlobalField(stringValue=lisi, intValue=0, booleanValue=false)
}
3.解析不完整的JSON
与其他未知字段类似,解析不完整的JSON(不包含Java类中所有字段的JSON)对于Jackson来说不是问题:
@Test
public void test27() throws IOException {
String jsonAsString = "{\"stringValue\":\"a\",\"booleanValue\":true}";
ObjectMapper mapper = new ObjectMapper();
MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
System.out.println(readValue);//MyDtoIgnoreUnknown(stringValue=a, intValue=0, booleanValue=true)
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
}