【问题标题】:Gson nested objects with an ArrayList带有 ArrayList 的 Gson 嵌套对象
【发布时间】:2018-05-11 10:20:08
【问题描述】:

从我的 Json 的内部 ArrayList 和变量中取出数据时遇到问题。我可以将我的 Json 读入字符串并打印出来,但是当我调用 fromJson 并访问生成的类时,我的数组列表为空,所有数据均为空白。

下面的示例代码。

我的 Json 字符串打印:

{

'ShippingList': {

'ShippingInfo': {

'ShipList_No': 'SP10000001',

'Ship_Date': 'Nov-14-2017'
                                                                        },

'ItemInfo': [{

'Item_SerialNumber': 'item0000001',

'Bin_Location': '3',

'QTY': '1'

},

{

'Item_SerialNumber': 'item0000002',

'Bin_Location': '3',

'QTY': '1'

},

{

'Item_SerialNumber': 'item0000003',

'Bin_Location': '3',

'QTY': '1'

},

{

'Item_SerialNumber': 'item0000004',

'Bin_Location': '3',

'QTY': '1'

},

{

'Item_SerialNumber': 'item0000005',

'Bin_Location': '3',

'QTY': '1'

}
]
}
}

Gson 代码:

Gson Gos = new Gson();
ShipList SL = Gos.fromJson(inList,ShipList.class);
String temtem = SL.getALI().get(0).getSerial();
Log.d("Proof! ","wadda " + temtem);

这只会打印:证明!瓦达

我的课程适合 Json 的内容,并且已经被序列化。我已经成功地创建了一个类并将其转换为 Json,但我无法正确地从 Json 转换为对象

【问题讨论】:

  • 上述 json 包含错误,这就是 GSON 不解析它的原因

标签: java arraylist gson


【解决方案1】:

您的代码的第一个问题是 json 使用双引号 ",而不是单引号 ' 来包含键和值。 json 的前几行应该是

{
  "ShippingList": {
    "ShippingInfo": {
      "ShipList_No": "SP10000001",

等等。

我在自己的机器上用 gson 2.7 版测试了这个格式正确的 json,它运行良好

Gson Gos = new Gson();
//set inList to your input .json
ShipList SL = Gos.fromJson(inList,ShipList.class);
String temtem = SL.shippingList.itemInfo.get(0).itemSerialNumber;
System.out.println(temtem);

它打印出item0000001。如果您修复了 json 的格式,但它仍然无法正常工作,我会检查其他一些事情是 inList 是否已正确初始化以包含您的 json 文本。

祝你好运!

【讨论】:

  • 谢谢伙计!我将 ' 更改为 " 并开始像魅力一样工作。不敢相信我犯了这样的错误!
猜你喜欢
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多