How will I decode this JSON using GSON (Multidimensional Array)?
I’m using GSON to decode the JSON string returned from our server. I didn’t have any issues before I came across this particular JSON returned from the API. The return format is as follows:
“Success”: 1, “Error”: [], “Data”: {“524”: {“id”:”524″}, “525”: {“
id”:”525″}}
For other returns, I treat the data as an array of classes I created myself, but for this return, it says it’s an object and not an array. So how should I format my class?
EDIT: The trouble I’m having is that the “524” and “525” fields are not static names. They depend on what the user’s credentials are. There may be fields 323, 324, 325, or a single field 123. It all depends. How can I handle this dynamically?
Resolved*
All I have to do is make the “data” a <String, Object>
HashMap in my custom class. Then after the first decoding, I turned ‘data’ into an array of type Object[]. Then for each Object[i], I convert it to a JSON string. After that, I used gson.fromJson() to transform it to what I originally wanted.
Solution
If the API gives inconsistent results and you end up finding a reason for this, one option is to resolve the object to GSON JSONObject o = gson.fromJson(String
) and then convert the data to a list by executing o.getElement("data").isList()
etc. if it is not a list )。
When you’re done, you can create an object from gson.fromJson(JSONObject,Class).
Another approach is to have two classes, one for each instance, but this seems sloppy if that’s the only reason to have two different classes.