gpt4 book ai didi

java - 解析嵌套 JSON 数组时卡住

转载 作者:行者123 更新时间:2023-12-02 10:20:08 25 4
gpt4 key购买 nike

我无法解析嵌套的 JSON 数组。这应该相当简单,但我似乎无法让它工作。

我有一个如下所示的 JSON 数组:

    {"currentPage":0,
"totalPages":1,
"totalSize":1,
"first":true,
"last":true,
"list"[{"date":"2018-11-07T09:34:25.042+0000",
"lastUpdated":"2018-11-07T09:34:25.266+0000",
"id"130674,
"active":true,
"address":null,
"storeMobileNumbers":
[{"id":130676,"mobile":"+201008005090","version":0
}]
}]
}

我尝试首先从列表中获取地址,然后从 storeMobileNumbers 中获取值。

我有一个用于列表的 POJO 类,现在我已经为 StoreMobileNumbers 创建了一个 POJO 类。

这就是我现在拥有的:

      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Type collectionType = new TypeToken<List<MyStore>>(){}.getType();
Type collection2 = new TypeToken<List<StoreMobileNumber>>({}.getType();
JSONObject obj = new JSONObject(json);
if (obj.has("list")) {
String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType);

JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.toJSONObject(obj1);
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);
}

我的 StoreMobileNumbersClass:

   public class StoreMobileNumber{

public Long id;
public String mobile;

}

到目前为止,我的努力还没有成功。我收到以下错误:

   org.json.JSONException: No value for storeMobileNumbers

有人可以帮我看看我在这里缺少什么吗?

最佳答案

更改为以下内容 -

String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType); // delete this not required

JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.getJsonObject(0); // change this to get first object from the JsonArray
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);

关于java - 解析嵌套 JSON 数组时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com