我是Android開發的新手,並且有一個關於如何使用GSON版本2.6.1將JSON字符串轉換爲類實例的問題。Android:使用GSON失敗的JSON到對象
我有一個需要轉換的字符串這樣的對象:
{
"Messages": [{
"ForwardMsg": true,
"IsAdmin": true,
"MsgBody": "Some text",
"SysInfo": null,
"Recipients": ["Some test"]
}, {
"ForwardMsg": true,
"IsAdmin": false,
"MsgBody": "Some other text",
"SysInfo": null,
"Recipients": ["Some test", "Some more text"]
}]
}
有了這個(http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/)爲靈感,我想出了以下內容: 我有一個類DemoMessageList,看起來像這樣的:
import java.util.List;
public class DemoMessageList {
private List< DemoMessage> messages;
public DemoMessageList() {
}
public List<DemoMessage> getMessages() {
return messages;
}
public void setMessages(List<DemoMessage> messages) {
this.messages = messages;
}
@Override
public String toString()
{
return "Messages ["+ messages + "]";
}
}
和A類DemoMessage,看起來像這樣:
import java.util.List;
public class DemoMessage {
private Boolean forwardMsg;
private Boolean isAdmin;
private String msgBody;
private String sysInfo;
private List<String> recipients;
public Boolean getForwardMsg() {
return forwardMsg;
}
public void setForwardMsg(Boolean forwardMsg) {
this.forwardMsg = forwardMsg;
}
public Boolean doForwardMsg() {
return forwardMsg;
}
public Boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getMsgBody() {
return msgBody;
}
public void setMsgBody(String msgBody) {
this.msgBody = msgBody;
}
public String getSysInfo() {
return sysInfo;
}
public void setSysInfo(String sysInfo) {
this.sysInfo = sysInfo;
}
public List<String> getRecipients() {
return recipients;
}
public void setRecipients(List<String> recipients) {
this.recipients = recipients;
}
}
當我做到這一點,嘗試變換:
public void test() {
String demoData = {"Messages": [{ "ForwardMsg": true, "IsAdmin": false,"MsgBody": "Some other text", "SysInfo": null, "Recipients": ["Some test", "Some more text"]}]}
Log.d("AsData ", "demoData: " + demoData);
Gson gson = new Gson();
DemoMessageList dmList = gson.fromJson(demoData, DemoMessageList.class);
Log.d("AsList ", "dmList: " + dmList.toString());
Log.d("ListSize ", "dmList - Size: " + String.valueOf(dmList.getMessages().size()));
}
我得到這樣的記錄:
demoData: {"Messages": [{ "ForwardMsg": true, "IsAdmin": false, "MsgBody": "Some other text", "SysInfo": null, "Recipients": ["Some test", "Some more text"]}]}
dmList: Messages [null]
dmList - Size: 0
爲什麼這裏會失敗? 請幫忙!!!