如何在没有 JsonArray 的情况下解析 JsonObject?
Posted
技术标签:
【中文标题】如何在没有 JsonArray 的情况下解析 JsonObject?【英文标题】:How to parse JsonObject without JsonArray? 【发布时间】:2021-12-19 02:07:25 【问题描述】:我有一个这样的 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 从“数据”标签中获取字符串对象,因为没有任何 json 数组可用于 foreach 标签。
我累了,我搜索了很多例子。我无法从 stacoverflow 找到任何解决方案。 谁能帮帮我?
【问题讨论】:
请提供足够的代码,以便其他人更好地理解或重现问题。 【参考方案1】:我不熟悉 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=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,信息=+1.5 进球,比率=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);
【讨论】:
以上是关于如何在没有 JsonArray 的情况下解析 JsonObject?的主要内容,如果未能解决你的问题,请参考以下文章
后台封装成jsonarray,前台js如何接收并存储到下拉列表中,急急急。。。
安卓。如何解析 JsonArray 中的 JsonArrays