0

I have this json file:

{
  "Update tree": {
    "average time": 0.01610115085649609,
    "best time": 0.003310859220941582,
    "count": 651,
    "success rate": 100,
    "worst time": 0.621779361692829
  },
  "Update renderables": {
    "average time": 0.1988377572034353,
    "best time": 0.0003510859220941582,
    "count": 649,
    "success rate": 100,
    "worst time": 12.8709652214104
  },
  "Before render": {
    "average time": 0.5206290903024032,
    "best time": 0.01522995241633128,
    "count": 188,
    "success rate": 100,
    "worst time": 81.06473259514415
  },
  "Rendering": {
    "average time": 4.425231035278629,
    "best time": 0.4979532268296139,
    "count": 214,
    "success rate": 100,
    "worst time": 71.34537426614806
  },
  "After render": {
    "average time": 0.06479598048728916,
    "best time": 0.0301288189105684,
    "count": 563,
    "success rate": 100,
    "worst time": 0.6413134310963844
  }
}

where I want to calculate the average of all avergaes in each json object how do I iterate through the json objects?

I am trying to get all avergaes values sum them up and calculate their average

EDIT:

I have this for loop which I want to iterate through each object (and not getting its member name but to actually iterate through the objects and get the values and then sum them up):

for(int i=0; i<json.size(); i++){
            sumAllAverages(json.getAsJsonObject());
        }

private static void sumAllAverages(JsonObject asJsonObject) {
        sum += Float.parseFloat(asJsonObject.get("average time").toString());
    }
1
  • I'll edit my question Commented Jul 23, 2020 at 7:41

2 Answers 2

2

With GSON you can just deserialize this to a map like:

Type type = new TypeToken<Map<String, Map<String, Double>>>() {}.getType();
Map<String, Map<String, Double>> map =
        new Gson().fromJson(getResourceStreamReader("file.json"), type);

getResourceStreamReader("file.json") is just a helper method to get your JSON from a resource file. It can be String or any reader.

To have all the average times (for example):

Set<Double> averageTimes = map.values().stream()
    .map(v -> v.get("average time")).collect(Collectors.toSet());

To inspect the averages from this map you can for example do this:

averageTimes.forEach(averageTime -> System.out.println(averageTime));

This produces:

0.01610115085649609
0.1988377572034353
0.5206290903024032
4.425231035278629
0.06479598048728916

Further you can use reduce to sum all the values and get the total average time;

Double totalAverageTime = averageTimes.stream()
            .reduce((a, b) -> a + b).orElse(0D) / averageTimes.size();

Inspect it:

System.out.println(totalAverageTime);

and you will see:

1.0451190028256505

Note: all this calculation may be done with yet fewer lines even in one lambda but for clarity and making it easier to follow I have splitted the phases.

Sign up to request clarification or add additional context in comments.

Comments

-1

This is how I do it in Jackson, gson should be fairly similar.

JsonNode time_Data;
    try {
      time_Data = new ObjectMapper().readTree(jsonTimes); // **this is your file as a string
      double sum = 0.0;
      if(time_Data!= null) {
        for (final JsonNode valuesPacket : time_Data) {
          sum += Double.parseDouble(valuesPacket.get("average time").asText());
        }
      }
      System.out.println("sum is :"+sum);
    } catch (JsonProcessingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

2 Comments

what maven dependancy are you using for the second line (e.g. readTree)
<dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.8.8</version> </dependency>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.