首页 > 解决方案 > JSON 到 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字段,而不必为and创建单独的类表示?someAttribute1property1someAttribute2somAttribute1someAttribute2

标签: javajsonxmljerseypojo

解决方案


您执行此操作的方式是Map<KeyType, ValueType>例如在您的情况下使用 a Map<String, String>will 来完成工作。代码应该这样工作:

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

推荐阅读