我想解析一个包含两个对象数组的JSON文件以及它们之间的关系,这是一个例子:
{
"a": [
{
"name": "one",
"id": 1
},
{
"name": "two",
"id": 2
},
{
"name": "three",
"id": 3
}
],
"b": [
{
"name": "cool",
"a_id": 1
},
{
"name": "better",
"a_id": 1
},
{
"name": "no_id",
"a_id": null
}
]
}
我想将这些实体映射到两个实体Aentity
和Bentity
,其中Aentity
应包含Bentities
数组。
我还希望Bentities
列表为null a_id。
这可能与杰克逊在一次解析中有关吗?怎么样?
注意:我问,因为我要解析的文件比较大。
答案 0 :(得分:1)
您可以通过id
上的a_id
和Bentity
属性来实现您所要求的内容,如下所示:
public class JacksonParsing {
private static final String JSON = "{\n" +
" \"a\": [\n" +
" {\n" +
" \"name\": \"one\",\n" +
" \"id\": 1\n" +
" },\n" +
" {\n" +
" \"name\": \"two\",\n" +
" \"id\": 2\n" +
" },\n" +
" {\n" +
" \"name\": \"three\",\n" +
" \"id\": 3\n" +
" }\n" +
" ],\n" +
" \"b\": [\n" +
" {\n" +
" \"name\": \"cool\",\n" +
" \"a_id\": 1\n" +
" },\n" +
" {\n" +
" \"name\": \"better\",\n" +
" \"a_id\": 1\n" +
" },\n" +
" {\n" +
" \"name\": \"no_id\",\n" +
" \"a_id\": null\n" +
" }\n" +
" ]\n" +
"}";
public static void main(String... args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Aentity result = objectMapper.readValue(JSON, Aentity.class);
System.out.println(result.getB().get(0).getName());
}
static class Aentity {
private List<Bentity> a;
private List<Bentity> b;
public Aentity() {
}
public List<Bentity> getA() {
return a;
}
public void setA(List<Bentity> a) {
this.a = a;
}
public List<Bentity> getB() {
return b;
}
public void setB(List<Bentity> b) {
this.b = b;
}
}
static class Bentity {
private String name;
private Integer id;
private Integer a_id;
public Bentity() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getA_id() {
return a_id;
}
public void setA_id(Integer a_id) {
this.a_id = a_id;
}
}
}
但是,Aentity
具有name
和id
属性的情况可能会更好,而Bentity
具有name
和a_id
属性(即不同的类型)都包含在不同的父对象中。