JSON到POJO-忽略某些嵌套属性

时间:2018-11-16 13:15:36

标签: java json xml jersey pojo

假设我有一个看起来像这样的JSON对象

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

以及下面的POJO类,将该实体读入

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

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

如何获取property1的{​​{1}}字段和someAttribute1的{​​{1}}字段,而不必为property1创建单独的类表示,并且someAttribute2

3 个答案:

答案 0 :(得分:1)

您可以通过使用Map<KeyType, ValueType>来实现此目的,例如,您可以使用Map<String, String>来完成工作。该代码应该像这样工作:

@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;
}

答案 1 :(得分:0)

在您的示例中,似乎很适合您的情况是在Person类中添加两个hashmap成员变量,如下所示:

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

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

@XmlElement(name = "someAttribute1")
private HashMap<String,String> someAttribute1;
}

@XmlElement(name = "someAttribute2")
private HashMap<String,String> someAttribute2;
}

答案 2 :(得分:0)

您可以结合使用@JsonProperty和类中的某些自定义逻辑,使用Jackson库来解开嵌套属性。

    public class Person {
      private String name;
      private int age;
      private String someAttribute1Property1;
    }

    @SuppressWarnings("unchecked")
    @JsonProperty("someAttribute1")
    private void unpackNested(Map<String,Object> someAttribute1) {
        this.someAttribute1= (String)brand.get("Property1");
       -------
    }
}

参考:https://www.baeldung.com/jackson-nested-values