繁体   English   中英

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

[英]How to parse JsonObject without JsonArray?

我有一个这样的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"
}}}

但是我无法使用 volley 从“data”标签中获取字符串对象,因为没有任何用于 foreach 标签的 json 数组。

我累了,我搜索了很多例子。 我无法从 stacoverflow 中找到任何解决方案。 任何人都可以帮助我吗?

一个简单的方法是使用大多数 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=Germany League, teamOne=Grossaspach, teamTwo=Offenbacher, date=05.11.2021 - 21.00, result=0, teamOneScore=0, teamTwoScore=0, info=+1.5进球,比率=1.19}
{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}
{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 进球数,比率=1.20}


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM