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.

3
  • Have you looked here? stackoverflow.com/questions/3763937/… Commented Aug 12, 2013 at 13:38
  • Ok, that works...I was missing Array to ArrayList conversion. Commented Aug 12, 2013 at 14:15
  • Great! Please answer question and accept your answeryourself so that it is marked answered Commented Aug 12, 2013 at 14:16

2 Answers 2

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)));
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this.

public class Category {
    int id = 0;
    ArrayList<Category> subCategories = new ArrayList<Category>()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.