[英]Json deserialization Java
我有一个简单的问题,假设我有这个 json
{
"outer-field":{
"outer-a":"something",
"outer-b":12345678,
"inner-field":{
"inner-a":false,
"inner-b":0.0,
"inner-c":29.99
}
}
}
以这种方式映射:
public class OuterObject {
@JsonProperty("outer-a")
public String outerA;
@JsonProperty("outer-b")
public Integer outerB;
@JsonProperty("inner-field")
public InnerObject innerField;
}
public class InnerObject{
@JsonProperty("inner-a")
public Boolean innerA;
@JsonProperty("inner-b")
public Double innerB;
@JsonProperty("inner-c")
public Double innerC;
我想知道是否可以通过使用一些自定义设置器/注释或其他东西来像这样在内部对象中保存一个外部字段:
public class InnerObject{
@JsonProperty("inner-a")
public Boolean innerA;
@JsonProperty("inner-b")
public Double innerB;
@JsonProperty("inner-c")
public Double innerC;
//how to map this?
@JsonProperty("outer-a")
public String outerA;
PS:由于json的复杂性,使用自定义反序列化是我最后的手段
如果有人问我如何解决我的问题,我决定使用自定义 Builder,通过使用内部的 withXXX 方法在创建期间将外部属性传递给内部对象
@Jacksonized
@JsonDeserialize(builder = OuterObject.Builder.class)
@AllArgsConstructor
@Data
public class OuterObject {
public String outerA;
public Integer outerB;
public InnerObject innerObject;
public static class Builder {
public String outerA;
public Integer outerB;
public InnerObject innerObject;
Builder withInnerObject(InnerObject innerObject) {
// set attributes here
innerObject.outerA = this.outerA
this.innerObject = innerObject
return this;
}
public OuterObject build() {
return new(outerA, outerB, innerObject)
}
Hope someone might find this helpful
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.