Jackson整理

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "test" (class com.acgist.api.request.pay.PayRequest), not marked as ignorable (3 known properties: "orderId", "requestTime", "sign"])
 at [Source: (String)"{"test":"test","orderId":"orderId","sign":"sign","queryId":"queryId"}"; line: 1, column: 10] (through reference chain: com.acgist.api.request.pay.PayRequest["test"])
	at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
	at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)

这个是由于将JSON对象转为Java对象时,JSON对象存在Java对象不存在的属性时会有这个异常。

解决办法:

// 添加注解
@JsonIgnoreProperties(ignoreUnknown = true)
// 添加代码
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如果是Java对象序列化时,不想序列化null属性,可以设置:

// 添加注解
@JsonInclude(Include.NON_NULL)
// 添加代码
mapper.setSerializationInclusion(Include.NON_NULL);
// 添加注解:已经过时
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)

序列化时忽略不需要序列化的字段:

// 属性注解
@JsonIgnore
// 类注解
@JsonIgnoreProperties(ignoreUnknown = true, value = {"sign"})