【问题标题】:Use gson to parse json array with both string and another array in it?使用 gson 解析包含字符串和另一个数组的 json 数组?
【发布时间】:2017-07-31 12:31:45
【问题描述】:

请看下面的json

{ "somekey" : 
    { "data" : [[
        "1", 
        "this is 2 ind index data", 
        ["one", "two", "three", "four", "five"]
    ]]}
}

以上是我的 json 数据的结构,它是一个包含 2 个字符串和一个数组的数组,如何使用 Gson 解析响应

以下是我写的模型类 BaseData.java

class BaseData
{
public SomeData somekey;
}

SomeData.java

class SomeData
{
ArrayList<ArrayList<String>> data
}

在得到响应后,我调用了常用的 gson 函数

 new  Gson().fromJson("above response string here", BaseData.class);

但我收到以下错误

07-31 17:26:14.824 28099-28099/ W/System.err: 原因: java.lang.IllegalStateException:应为字符串,但为 BEGIN_ARRAY 在第 1 行第 253 列路径 $。

我知道这是因为我制作的数组模型我只制作了接受字符串的数组但是我该如何修复它,以便我可以同时接受字符串和数组以及这样的数组响应

谢谢

【问题讨论】:

    标签: java android arrays json gson


    【解决方案1】:

    您必须使用Arraylist&lt;Arraylist&lt;Object&gt;&gt;,因为您在该列表中有不同的类型

    您的提取代码必须稍后转换以获得正确的类型

    【讨论】:

      【解决方案2】:

      你需要这样的结构:

      class BaseData {
           SomeKey somekey;
      }
      class SomeKey {
           List<ArrayEntity> data;
      }
      class ArrayEntity {
           int firstVar;
           String secondVar;
           List<String> thirdVar;
      }
      

      并像这样使用它:

       new  Gson().fromJson("above response string here", BaseData.class);
      

      【讨论】:

      • ArrayEntity 不是 JSON 中的对象
      • as @cricket_007 ArrayEntity 不是 JSON 中的对象
      • @Ramz 我的错。如果 ArrayEntity 相同,在 SomeKey 中我们需要使用 List>。如果不是 - List> 并手动解析它
      • List> 出于同样的原因是错误的。内部列表中没有对象,只有字符串和列表
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多