[英]Jackson Unwrap / Wrap Object
我有一个spring boot项目,我有一个这样的类:
@Value
public class A {
@JsonUnwrapped
OrderKey key;
String description;
B b;
@Value
public static class B {
String description;
}
}
@Value
public class OrderKey {
@JsonProperty( "_key" )
String id;
}
我有mixins,但为了简洁,在这个例子中添加了Annotations。 序列化为JSON时这很有用,问题是当我尝试反序列化时,如果存在一些@JsonWrapped
注释,它可能会起作用。
简而言之,我正在尝试使用ArangoDB,我可以创建/读取文档,但我需要使用自己的Value Objects,不幸的是我不能将键用作String,它由OrderKey
封装。 @Value
注释来自@Value
项目。
有没有办法实现这个目标?
您可以尝试在使用@JsonCreator
注释的class A
定义构造@JsonCreator
。 然后,Jackson可以使用此构造函数创建A
对象,并将您希望在JSON文档中的字段映射到A
的字段。 简化示例:
@Value
public class A {
@JsonUnwrapped
OrderKey key;
String description;
@JsonCreator
public A(@JsonProperty("key") String key,
@JsonProperty("description") String description) {
this.key = new OrderKey(key);
this.description = description;
}
}
请注意, A
此构造函数将阻止创建@AllArgsConstructor
隐含的@AllArgsConstructor
构造@Value
。
也可以使用Java 8和一些额外的模块来避免构造函数注释。 检查该煤矿例如对方的回答。
我最终在mixin本身内进行了序列化/反序列化,这样我可以避免使用@JsonUnwrapped
注释和另一个mixin。
混入:
public class OrderMixin {
@JsonDeserialize( using = OrderKeyDeserializer.class )
@JsonSerialize( using = OrderKeySerializer.class )
@JsonProperty( "_key" )
OrderKey key;
@JsonProperty( "description" )
String description;
@JsonProperty( "amount" )
String amount;
@JsonProperty( "operation" )
Order.Operation operation;
@JsonProperty( "creationDate" )
LocalDateTime creationDate;
public static class OrderKeySerializer extends JsonSerializer<OrderKey> {
public OrderKeySerializer() {
super( OrderKey.class );
}
@Override
public void serialize( OrderKey value, JsonGenerator gen, SerializerProvider provider ) throws IOException {
gen.writeString( value.getOrderId() );
}
}
public static class OrderKeyDeserializer extends JsonDeserializer<OrderKey> {
public OrderKeyDeserializer() {
super( OrderKey.class );
}
@Override
public OrderKey deserialize( JsonParser jsonParser, DeserializationContext context ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree( jsonParser );
return OrderKey.get( node.asText() );
}
}
}
价值对象:
@Value
public class Order implements Serializable {
private static final long serialVersionUID = 901109456762331944L;
OrderKey key;
String description;
String amount;
Operation operation;
LocalDateTime creationDate;
@Value
public static class Operation {
String id;
String description;
String status;
LocalDateTime creationDate;
}
}
@Value
public class OrderKey implements Serializable {
private static final long serialVersionUID = -8102116676316181864L;
private String orderId;
public static OrderKey get( String orderId ) {
return new OrderKey( orderId );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.