Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Gson to parse Json array and object with no name

I know there are many JSON with GSON questions but none of them relate to me directly. My JSON is formatted differently.

I have a JSON data I want to parse using GSON which looks like the following:

[
   {
    "foo":"1",
    "bar":[ { "_id":"bar1"} ],
    "too":["mall", "park"]
   }
]

And I have the model Classes:

ItemArray Class

public class ItemArray
{
   List<Item> itemArray;

   //Get set here
}

Item Class

public class Item
{
   String foo;
   List<Bar> bar;
   List<String> too;

   //Get set here
}

Bar Class

public class Bar
{
   String id;

   //Get set here
}

Heres the question. Is the JSON in the correct format? If so, are the model classes in the correct format?

If not, please shove me in the right direction. Thank you in advance!

PS. I can modify the JSON data format if need be.

like image 812
Muhammad Aljunied Avatar asked Dec 06 '12 02:12

Muhammad Aljunied


2 Answers

According to your json, you should simply have :

public class ItemArray extends List<Item> {
}

if you want to keep you java class and change your json it should be :

{
 itemArray: [
     {
      "foo":"1",
      "bar":[ { "_id":"bar1"} ],
      "too":["mall", "park"]
     }
  ]
}

Oh, and there is a mismatch with the id and _id for Bar :

public class Bar
{
   String _id;

   //Get set here
}

You could also use an annotation to change the field's name during Json de/serialization.

And last but not least, consider typing your values better. Don't see any data as strings if they are not, you will not a lot of processing in java code to convert things. For instance :

"foo" : 1,

and see foo as an int data member, not a String.

like image 164
Snicolas Avatar answered Oct 21 '22 13:10

Snicolas


Some times we get JsonArray [ {..} , {..} ] as a response (without 'itemArray' name like yours) In that case you can use following code

Type fooType = new TypeToken<ArrayList<Item>>() {}.getType();
List<Item> array = new Gson().fromJson(response, fooType);

find more about this Official doc - Gson Array-Examples

like image 41
Bharatesh Avatar answered Oct 21 '22 14:10

Bharatesh