Java – parsing JSON objects and JSON arrays using gson
I have a JSON that is a single object or an array of the same object Is there any way to parse this data using gson, which will distinguish between a single object and an array?
My only solution at present is to parse JSON manually and surround it with try catch First, I'll try to parse it into a single object, if it fails, it will throw an exception, and then I'll try to parse it into an array
I don't want to parse manually, it will always need me It's an idea of what happened
public class ObjectA implements Serializable{ public String variable; public ObjectB[] objectb; //or ObjectB objectb; public ObjectA (){} }
This is an object that can be an array or a single object
public class ObjectB implements Serializable{ public String variable1; public String variable2; public ObjectB (){} }
Then when interacting with the JSON response I'm doing this
Gson gson = new Gson(); ObjectA[] objectList = gson.fromJson(response,ObjectA[].class);
When an array of objecta is serialized, JSON contains an array of objectb or a single object
[ { "variable": "blah blah","objectb": { "variable1": "1","variable2": "2" } },{ "variable": "blah blah","objectb": [ { "variable1": "1","variable2": "2" },{ "variable1": "1","variable2": "2" } ] } ]
Solution
I just changed objectb [] to list < objectb > to enter objecta declaration
ArrayList<ObjectA> la = new ArrayList<ObjectA>(); List<ObjectA> list = new Gson().fromJson(json,la.getClass()); for (Object a : list) { System.out.println(a); }
This is my result:
{variable=blah blah,objectb={variable1=1,variable2=2}} {variable=blah blah,objectb=[{variable1=1,variable2=2},{variable1=1,variable2=2}]}
I think in the age of complete generics, if you don't have specific requirements, you can switch from array to list, you can also use gson, and you can use flexible parsing to get many benefits