簡體   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