3

I've the following JSON structure:

[
 {
  "id": 1,
  "subcategories": [
   {
    "id": 2,
    "subcategories": [
    ]
   },
   {
    "id": 3,
    "subcategories": [
    ]
   }
  ]
 },
 {
  "id": 4,
  "subcategories": [
   {
    "id": 5,
    subcategories: [
    ]
   }
  ]
 }
]

The model class for a Category (some fields like title are omitted for simplicity), for reflecting JSON structure:

public class Category {
    int id = 0;
    ArrayList<Category> subCategories = null;
}

I'm trying to parse that with Gson library (2.2.4), having hard times deserializing inner array to arraylist:

Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<Category>>(){}.getType();
ArrayList categories = gson.fromJson(json, collectionType);

Category.subCategories is always null.

Jumpa
  • 4,319
  • 11
  • 52
  • 100
  • Have you looked here? http://stackoverflow.com/questions/3763937/gson-and-deserializing-an-array-of-objects-with-arrays-in-it?rq=1 – Tala Aug 12 '13 at 13:38
  • Ok, that works...I was missing Array to ArrayList conversion. – Jumpa Aug 12 '13 at 14:15
  • Great! Please answer question and accept your answeryourself so that it is marked `answered` – Tala Aug 12 '13 at 14:16

2 Answers2

8
gson.fromJson(json, Category[].class)

worked good for me. If you want an ArrayList instead of an Array:

new ArrayList<Category>(Arrays.asList(gson.fromJson(json, Category[].class)));
Jumpa
  • 4,319
  • 11
  • 52
  • 100
-1

Try this.

public class Category {
    int id = 0;
    ArrayList<Category> subCategories = new ArrayList<Category>()
}
PrvN
  • 2,385
  • 6
  • 28
  • 30