我的JSON看起来如下:
"message_defaults": {
"LabResultsRequestDefaultMessage": {
"MsgTypeId": 8,
"StaffId": 122,
"StaffName": "Willis,Sam",
"FirstName": "Sam",
"MI": "D",
"LastName": "Willis",
"DefaultMessage": "Lab Department"
},
"ReferralRequestDefaultMessage": {
"MsgTypeId": 6,
"StaffId": 122,
"StaffName": "Willis,Sam",
"FirstName": "Sam",
"MI": "D",
"LastName": "Willis",
"DefaultMessage": "Physican"
},
"MessageComposeDefaultMessage": {
"MsgTypeId": 1,
"StaffId": 122,
"StaffName": "Willis,Sam",
"FirstName": "Sam",
"MI": "D",
"LastName": "Willis",
"DefaultMessage": "Office Manager/Willis Sam"
}
}
现在message_defaluts中的每个elemet都具有相同的结构(假设一个名为MessageDefault.java的POJO).那么如何将所有消息默认值作为List< MessageDefault> ??
我正在使用gson进行解析.我也无法改变JSON响应.
编辑::
MessageDefault.java
public class MessageDefault{
private String defaultMessage;
private String firstName;
private String lastName;
private String mI;
private int msgTypeId;
private int staffId;
private String staffName;
public String getDefaultMessage(){
return this.defaultMessage;
}
public void setDefaultMessage(String defaultMessage){
this.defaultMessage = defaultMessage;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getMI(){
return this.mI;
}
public void setMI(String mI){
this.mI = mI;
}
public int getMsgTypeId(){
return this.msgTypeId;
}
public void setMsgTypeId(int msgTypeId){
this.msgTypeId = msgTypeId;
}
public int getStaffId(){
return this.staffId;
}
public void setStaffId(int staffId){
this.staffId = staffId;
}
public String getStaffName(){
return this.staffName;
}
public void setStaffName(String staffName){
this.staffName = staffName;
}
}
它只是所有message_defualts的结构.但是在JSON中,message_defualts的每个子节点都有不同的名称,如LabResultsRequestDefaultMessage,ReferralRequestDefaultMessage等,它们反映在POJO MessageDefault.java中.但是从JSON我想要它们的列表.
谢谢.
解决方法:
您可以在不更改json结构的情况下执行以下操作.
Type mapType = new TypeToken<Map<String, MessageDefault>>() {}.getType();
Map<String, MessageDefault> messagesMap = gson.fromJson(json, mapType);
List<MessageDefault> messages = new ArrayList<MessageDefault>(messagesMap.values());