Skip to content
Advertisement

How to parse JsonObject without JsonArray?

I have an json like this:

{"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"
}}}

But I could not get string objects from “data” tag using volley because there is no any json array to foreach tag.

I tired and I search so much examples. I could’nt find any solution from stacoverflow. Any one can help me?

Advertisement

Answer

I am not familiar with Volley, but a straightforward way is to desceailize your JSON string to a Map with most JSON libraries(e.g., Jackson), then you can get the content of field data and traverse it as follows:

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);

Console output:

{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}
{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 Goal Over, ratio=1.20}


You can also get the same result by using Jayway JsonPath:

Map<String, Object> resultMap = JsonPath.parse(jsonStr).read("$.data");
resultMap.entrySet().stream()
        .map(Map.Entry::getValue)
        .forEach(System.out::println);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement