每次我将JSON对象数组映射到POJO时,总是得到最后一个对象。
JSON是一个对象数组,我有一个POJO与JSON的每个对象关联。但是当我映射到POJO数组中时,总是得到1个对象。
这是JSON:
[ {
"event" : {
"Id" : "123456789",
"Name" : "An event1 name"
},
"branch" : {
"Id" : "112233445566",
"Name" : "A branch1 name",
},
"user" : {
"Id" : "9988776655",
"FirstName" : "John",
"LastName" : "Doe",
},
"event" : {
"Id" : "abcdef",
"Name" : "An event2 name"
},
"branch" : {
"Id" : "885522",
"Name" : "A branch2 name",
},
"user" : {
"Id" : "996633",
"FirstName" : "Jane",
"LastName" : "Doe",
}
} ]
POJO:
public class RdV {
private Event event;
private Branch branch;
private User user;
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch= branch;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "RdV [\n"
+ event + "\n"
+ branch + "\n"
+ user + "\n"
+ "]";
}
}
public class Event {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
}
其他POJOS,Branch和User与事件类似。
当我使用以下内容时:
List<RdV> rdv = Arrays.asList(objectMapper.readValue(jsonString, RdV[].class));
我得到的只是最后一个对象(列表的大小是1,而不是2):
==> RdV [
Event {
id="abcdef",
name="An event2 name"
}
Branch {
id="885522",
name="A branch2 name"
}
User {
id="996633",
lastName="Doe",
firstName="Jane"
}
]
你知道代码出了什么问题吗?
谢谢。
答案 0 :(得分:0)
您的JSON没有两个单独的对象-只有一个具有Branch,Event和User双重属性的对象,您应该将其更改为
[
{
"event": {
"Id": "123456789",
"Name": "An event1 name"
},
"branch": {
"Id": "112233445566",
"Name": "A branch1 name"
},
"user": {
"Id": "9988776655",
"FirstName": "John",
"LastName": "Doe"
}
},
{
"event": {
"Id": "abcdef",
"Name": "An event2 name"
},
"branch": {
"Id": "885522",
"Name": "A branch2 name"
},
"user": {
"Id": "996633",
"FirstName": "Jane",
"LastName": "Doe"
}
}
]