我嘗試在gson的幫助下反序列化json字符串。雖然gson.fromJson我得到以下錯誤:gson - >「類xyz的無參數構造函數」與數組
No-args constructor for class xyz; does not exist. Register an InstanceCreator with Gson for this type to fix this problem
我試圖使用InstanceCreate但我沒有得到這個運行。 我希望你能幫助我。
JSON字符串
[
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
},
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 12:38:12"
}
]
根據GSON我不得不切割第一和最後一個字符( 「[」 和 「]」) 根據http://www.jsonlint.com/字符串是正確的字符...:?:
的代碼看起來像這樣:
public class License {
public String prog;
public String name;
public String computername;
public String date;
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
}
String JSONSerializedResources = "json_string_from_above"
try
{
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
License[] lic = null;
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
for (License license : lic) {
Toast.makeText(getApplicationContext(), license.name + " - " + license.date, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
認爲克里斯
它仍然是一樣的。當我反序列化不是在許可證[],而是在許可證上,並且只將一個對象放入json字符串中。甚至沒有公共構造函數 – 2010-11-23 08:15:30
爲什麼你使用`j = new JSONObject(JSONSerializedResources)`? – 2010-11-23 09:12:07