我尝试在 gson 的帮助下反序列化一个 json 字符串。虽然 gson.fromJson 我收到以下错误:
xyz 类的无参数构造函数;不存在。为这个类型注册一个 InstanceCreator 到 Gson 来解决这个问题
我尝试使用 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();
}
问候克里斯