I’m having some trouble parsing a JSON that I obtain from my DB to my Java (Android) Application. I hope you can help me out:
This is the Json that I have:
<br>
[{<br>
"ID" : "1",<br>
"name" : "Test name",<br>
"type" : "1",<br>
"Desc" : "blablabla",<br>
"minNum" : "0",<br>
"maxNum" : "12",<br>
"Num" : "8",<br>
"bool1" : "0",<br>
"bool2" : "1",<br>
"bool3" : "1",<br>
"date" : "2012-04-01 23:00:00",<br>
"double1" : "39.47208",<br>
"doubl2" : "-0.3556063",<br>
"someText" : "ajayeah",<br>
"number" : "15",<br>
"anotherNumber" : "1234"<br>
}, {"ID" : "2",<br>
"name" : "Test name",<br>
"type" : "1",<br>
"Desc" : "blablabla",<br>
"minNum" : "0",<br>
"maxNum" : "12",<br>
"Num" : "8",<br>
"bool1" : "0",<br>
"bool2" : "1",<br>
"bool3" : "1",<br>
"date" : "2012-04-01 23:00:00",<br>
"double1" : "39.47208",<br>
"doubl2" : "-0.3556063",<br>
"someText" : "ajayeah",<br>
"number" : "15",<br>
"anotherNumber" : "1234"<br>
}]<br>
(The names are ovbiously not the ones I wrote here :P)
I have all that as a String (checked, OK), for example in a variable called responseString;
and then I’ve tried all possible ways to do the conversion but it always fails. I’ve tried to get it as an Object removing ‘[‘ ‘]’, as an Array (things I achieved but then this line fails):
MyClassList MyClas = new Gson().fromJson(responseString, MyClassList.class);
The error is:
com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
(with other tests converting it first to object or array, the error is with BEGIN_STRING)
Could it be because I’m using booleans, and Calendar type (in Date) and it’s not supported by Gson library?
Well, I hope you can get my out of here because I’m going mad.
Thanks 🙂
Don’t use Calendar, that was my problem. Instead, you may use Date and it works. Also, I don’t know why, booleans like “0”|”1″ don’t work. Like “true”|”false” yes.
The problem is that you are trying to deserialize an array into a class that is not an array, and that won’t work for obvious reasons. Since you know the array type just use any instance of MyClass[] to get the class from. You can create one at any time. Alternately pass in
MyClass[].class(i.eMyClass.classis not the same asMyClass[].class)Here is an example that will run out of the box if you create a log4j.properties file (Or convert the loggers to System outs: