Search code examples
javajsonxmljerseypojo

JSON to POJO - Ignore certain nested properties


Suppose I have a JSON object that looks like this

{
  "name":"John",
  "age":30,
  "someAttribute1": {
      "property1":"example1",
      "property2":"example2"
  },
  "someAttribute2": {
      "property1":"example1",
      "property2":"example2"
  }
}

And the following POJO class to read that entity into

@XmlRootElement      
public class Person {
  @XmlElement(name = "name")
  private String name;

  @XmlElement(name = "age")
  private int age;
}

How can I get the property1 field of someAttribute1 and the property1 field of someAttribute2, without having to create a separate class representation for somAttribute1 and someAttribute2?


Solution

  • The way you do this is by using Map<KeyType, ValueType> for example in your case a Map<String, String> will do the work. The code should work like that:

    @XmlRootElement      
    public class Person {
      @XmlElement(name = "name")
      private String name;
    
      @XmlElement(name = "age")
      private int age;
    
      @XmlElement(name = "someAttribute2")
      private Map<String, String> someAttributeTwo;
    
      @XmlElement(name = "someAttribute1")
      private Map<String, String> someAttributeOne;
    }