如何在没有JsonArray的情况下解析JsonObject



我有一个json,如下所示:

{"status": "ok","data": {
"0": {
"id": "1901",
"price": "0",
"userBought": "0",
"leagueName": "Germany League",
"teamOne": "Grossaspach",
"teamTwo": "Offenbacher",
"date": "05.11.2021 - 21.00",
"result": "0",
"teamOneScore": "0",
"teamTwoScore": "0",
"info": "+1.5 Goal Over",
"ratio": "1.19"
},
"1": {
"id": "1900",
"price": "0",
"userBought": "0",
"leagueName": "France League",
"teamOne": "FC Villefranche-Beaujolai",
"teamTwo": "US Avranches",
"date": "05.11.2021 - 21.00",
"result": "0",
"teamOneScore": "0",
"teamTwoScore": "0",
"info": "+1.5 Goal Over",
"ratio": "1.25"
},
"2": {
"id": "1899",
"price": "0",
"userBought": "0",
"leagueName": "Germany League",
"teamOne": "Holstein Kiel",
"teamTwo": "Dynamo Dresden",
"date": "05.11.2021 - 20.30",
"result": "0",
"teamOneScore": "0",
"teamTwoScore": "0",
"info": "+1.5 Goal Over",
"ratio": "1.20"
}}}

但我无法从";数据";标记,因为foreach标记没有任何json数组。

我累了,找了那么多例子。我找不到堆栈溢出的任何解决方案。有人能帮我吗?

我不熟悉Volley,但一个简单的方法是用大多数JSON库(例如,Jackson(将JSON字符串解密为Map,然后您可以获得字段data的内容并按如下方式遍历它:

ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> resultMap = objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
((Map<String, Object>) resultMap.get("data")).entrySet().stream()
.map(Map.Entry::getValue)
.forEach(System.out::println);

控制台输出:

{id=1901,price=0,userBought=0,leagueName=德国联赛,teamOne=Grossaspach,teamTwo=Offenbacher,日期=2021年11月5日-21时,结果=0,teamOneScore=0,teamTwoScore=0,信息=+1.5进球数,比率=1.19}
{id=1900,price=0,userBought=0,leagueName=法甲,teamOne=博若莱足球俱乐部,teamTwo=美国Avranches,日期=2021年11月5日-21时,结果=0,teamOneScore=0,teamTwoScore=0,信息=+1.5进球数,比率=1.25}
{id=1899,price=0,userBought=0,leagueName=德国联赛,teamOne=荷尔斯泰因基尔,teamTwo=德累斯顿迪纳摩,日期=2021年11月5日-20.30,结果=0,teamOneScore=0,teamTwoScore=0,信息=+1.5进球数,比率=1.20}


您也可以使用Jayway JsonPath:获得相同的结果

Map<String, Object> resultMap = JsonPath.parse(jsonStr).read("$.data");
resultMap.entrySet().stream()
.map(Map.Entry::getValue)
.forEach(System.out::println);

相关内容

  • 没有找到相关文章

最新更新