I’m having troubles with the deserialization of a Json:
I get this error:
“No-args constructor for class Categoria: does not exist. Register an InstanceCreator with Gson for this type to fix this problem”
public class getElements {
String [] getEl (String url) throws ClientProtocolException, IOException {
Categoria c = null;
Categoria[] cArray = null;
String [] c1Array = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://10.0.2.2:3000/"+url);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String stringa = "{\"categorium\":{\"created_at\":\"2011-06-09T08:57:41Z\",\"c1\":\"rete stradale\",\"updated_at\":\"2011-06-09T08:57:41Z\",\"id\":1}}";
Gson json=new Gson();
try{
cArray=json.fromJson(stringa, Categoria[].class);
Log.i("ELEMENTO", ""+cArray);
}catch(JsonParseException e){
Log.i("error","JsonParseException");
}
c1Array = new String[cArray.length];
for (int i=0; i<cArray.length; i++) {
c1Array[i] = cArray[i].c1;
}
return c1Array;
}
}
Categorium class:
public class Categoria {
public String created_at;
public String c1;
public String updated_at;
public int id;
public Categoria() {
this.created_at = "";
this.c1="";
this.updated_at = "";
this.id = 0;
}
}
This is the Json. I want to bring al the “c1” into a String array, to built a snippet!
[
{
"categorium": {
"created_at": "2011-06-09T08:57:41Z",
"c1": "rete stradale",
"updated_at": "2011-06-09T08:57:41Z",
"id": 1
}
},
{
"categorium": {
"created_at": "2011-06-09T13:50:29Z",
"c1": "servizi pubblici",
"updated_at": "2011-06-09T13:50:29Z",
"id": 2
}
},
{
"categorium": {
"created_at": "2011-06-09T13:50:37Z",
"c1": "illuminazione",
"updated_at": "2011-06-09T13:50:37Z",
"id": 3
}
},
{
"categorium": {
"created_at": "2011-06-09T13:50:46Z",
"c1": "inquinamento",
"updated_at": "2011-06-09T13:50:46Z",
"id": 4
}
},
{
"categorium": {
"created_at": "2011-06-09T13:50:54Z",
"c1": "vandalismo",
"updated_at": "2011-06-09T13:50:54Z",
"id": 5
}
},
{
"categorium": {
"created_at": "2011-06-09T13:51:00Z",
"c1": "abbandono",
"updated_at": "2011-06-09T13:51:00Z",
"id": 6
}
},
{
"categorium": {
"created_at": "2011-06-15T08:33:17Z",
"c1": "altro",
"updated_at": "2011-06-15T08:33:17Z",
"id": 8
}
}
]
Answer to latest version of question:
Answer to original version of question:
That’s a terrible error message from Gson for the situation. I suggest logging an issue with them.
As posted in the current version of the question, the problem is you’re trying to deserialize a JSON object as an array. Easy solutions to this problem are to either change the JSON into an array, or deserialize it as an object.
Here’s an example that changes the JSON to have an array, and changes other things into what I guess you’re trying to achieve.