Spring boot @JsonProperty to map nested object through parent.child path

5.4k Views Asked by At

I have the following Data structure coming to my server through an Http call

person {
  name: "xyz",
  age: 30,
  status: {
    cd: "M",
    desc: "Married"
  }
}

Then I have the following entity class

@Setter
@Getter
public class Person {
  private String name;

  private int age;

  @JsonProperty("status.cd")
  private String status_cd;

  @JsonProperty("status/desc")
  private String status_desc;
}

Either way I try I'm not able to get spring boot to match the json property text (these two values are always null)... is that doable & if so, how?

the final JSON I need to be produced is the following

{
  name: "XYZ",
  age: 30,
  status_cd: "M",     // <-- Child attached to parent (flattened)
  status_desc: "Married"  // <-- Child attached to parent (flattened)
}

So basically I need to attach my child info to the parent.

UPDATE I was able to get one of the properties flattened with the parent by using a custom JsonDeserializer as follows

public class nameDeserializer extends JsonDeserializer<String> {
  @Overrde
  public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    PersonStatus st = p.valueAs(PersonStatus.class)
    return st.getStatusCd();
}

This works for only one property set with @JsonDeserialize(using = nameDeserializre.class) per class.... once I attach two deserializers to two properties, I start getting errors about json exceptions.

Thank you

1

There are 1 best solutions below

2
On

Try something like this

public class Person {
  private String name;

  private int age;

 private Status status;
 
 //your getter setter
}

public class Status {

      private String cd;

      private String desc;
      
      // getter setter
      
}