GSON:如何解析嵌套对象?

时间:2014-05-30 00:23:54

标签: android json gson

我有一个JSON:

[{
   "id": 100500,
   "products": [...array of JSON Objects...],
   "areas": [...array of JSON Objects...],
   ...(30 more fields)
},
{...},
....]

和班级商店:

public class Store {
      public  int id;
      public  List<Product> products;
      public  List<Area> areas;
      public ...(30 more fields)
}
好的,它运作正常。但服务器可以响应下一个json:

[{
   "id": 100500,
   "products": [1, 2, 3, 4...], << int array
   "areas": [5, 6, 7, 8...],    << int array
   ...(30 more fields)
},
{...},
....]

如您所见,“产品” - 是ID数组,但不是真实对象“Product”的数组。我如何正确解析这个json到类Store(即从数组中创建带有id的Products列表)?

1 个答案:

答案 0 :(得分:0)

您可能需要破解此服务器端设计决策。假设您无法预测服务器将返回的数据类型:

我要做的是使用class StoreB列表创建Integer

public class StoreB {
      public  int id;
      public  List<Integer> products;
      public  List<Integer> areas;
      public ...(30 more fields)
}

现在您可以尝试将JSON解析为原始的Store类。将其包装在GSON解析异常中,以便在失败时捕获它,并尝试反序列化为StoreB

相关问题