Jackson整理

0

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"})

追加字段

/**
 * 编辑判断
 * 
 * @author acgist
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@JsonAppend(props = @JsonAppend.Prop(value = EditableFieldWriter.class, name = "editable"))
@JacksonAnnotationsInside
public @interface Editable {
    
    /**
     * @return 类型
     */
    ResCheck.Type value();

}

枚举翻译

/**
 * 枚举翻译
 * 
 * @author acgist
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@JsonSerialize(using = TransferSerializer.class, nullsUsing = TransferSerializer.class)
@JacksonAnnotationsInside
public @interface Transfer {

	/**
	 * @return 枚举组
	 */
	String[] group();
	
}