我有以下 JSON结构: [ { "id": 1, "subcategories": [ { "id": 2, "subcategories": [ ] }, { "id": 3, "subcategories": [ ] } ] }, { "id": 4, "subcategories": [ { "id": 5, subcategories: [ ] } ] }] 类别的模型类(为简单起见,省略了
[ { "id": 1, "subcategories": [ { "id": 2, "subcategories": [ ] }, { "id": 3, "subcategories": [ ] } ] }, { "id": 4, "subcategories": [ { "id": 5, subcategories: [ ] } ] } ]
类别的模型类(为简单起见,省略了一些像title这样的字段),
用于反映JSON结构:
public class Category { int id = 0; ArrayList<Category> subCategories = null; }
我正在尝试用Gson库解析它(2.2.4),很难将内部数组反序列化为arraylist:
Gson gson = new Gson(); Type collectionType = new TypeToken<ArrayList<Category>>(){}.getType(); ArrayList categories = gson.fromJson(json, collectionType);
Category.subCategories始终为null.
gson.fromJson(json, Category[].class)
对我有用.如果你想要一个ArrayList而不是一个Array:
new ArrayList<Category>(Arrays.asList(gson.fromJson(json, Category[].class)));