【问题标题】:How to parse JsonObject without JsonArray?如何在没有 JsonArray 的情况下解析 JsonObject?
【发布时间】: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 找到任何解决方案。 谁能帮帮我?

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: java android json jsonparser


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2021-04-19
    • 2012-03-23
    相关资源
    最近更新 更多