假设我有一个看起来像这样的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
?
答案 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");
-------
}
}