i have a simple question, let’s say I have this json
{ "outer-field":{ "outer-a":"something", "outer-b":12345678, "inner-field":{ "inner-a":false, "inner-b":0.0, "inner-c":29.99 } } }
Mapped this way:
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;
I was wondering if it was possible to just save an outer field in the inner object like this by using some custom setter/annotation or something:
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: using a custom deserialization is my last resort due to the complexity of the json
Advertisement
Answer
If anyone was asking how I solve my problem, I decided to use a custom Builder by using the withXXX methods inside to pass the outer attributes to the inner object during creation
@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