问题描述
我尝试反序列化一个JSON字符串GSON的帮助。虽然gson.fromJson我收到以下错误:
i try to deserialize a json string with the help of gson. While gson.fromJson I get the following error:
类XYZ无参数的构造函数;不存在。注册GSON的InstanceCreator这种类型来解决这个问题。
我试图用一个InstanceCreate工作,但我没有得到这个运行。
我希望你能帮助我。
I tried to work with an InstanceCreate but I didn't get this running.I hope you can help me.
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"
}
]
([和])
根据字符串与字符正确...?
according to gson I have to cut the first and last chars ("[" and "]")according to http://www.jsonlint.com/ the string is with the chars correct... :?:
在code看起来像:
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();
}
至于克里斯
推荐答案
试着让你的构造公开,让GSON实际上可以访问它。
Try making your constructor public, so that gson can actually access it.
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
但自从Java创建一个默认的构造函数,你可以只使用:
but since Java creates a default constructor, you could just use:
public class License {
public String prog = "";
public String name = "";
public String computername = "";
public String date = "";
}
更新:
这真的很简单:的JSONObject
预计JSON对象{..}。您应该使用 JSONArray
其中预计[...]。
It's really quite trivial: JSONObject
expects a Json object "{..}". You should use JSONArray
which expects "[...]".
我想它和它的作品。你还是应该更改许可
类如上所述。
I tried it and it works. You should still change License
class as noted above.
这篇关于GSON - > "类XYZ&QUOT无参数的构造函数;使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!