0

I'm pulling some JSON down from a server, I'm parsing it and inserting into a Hashmap<>:

Edit I've added an example of the JSON response bellow, it wont always have this structure.

JSON:

 "metric_data": {
"from": "2015-10-29T21:28:14+00:00",
"to": "2015-10-29T21:58:14+00:00",
"metrics": [
  {
    "name": "Agent/MetricsReported/count",
    "timeslices": [
      {
        "from": "2015-10-29T21:26:00+00:00",
        "to": "2015-10-29T21:27:00+00:00",
        "values": {
          "average_response_time": 66,
          "calls_per_minute": 1,
          "call_count": 1,
          "min_response_time": 66,
          "max_response_time": 66,
          "average_exclusive_time": 66,
          "average_value": 0.066,
          "total_call_time_per_minute": 0.066,
          "requests_per_minute": 1,
          "standard_deviation": 0
        }

Java:

 OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(names);
        wr.flush();


        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        wr.close();
        reader.close();

        JSONObject json = new JSONObject(sb.toString());
        JSONObject metricsData = json.getJSONObject("metric_data");
        JSONArray metrics = metricsData.getJSONArray("metrics");
        JSONObject array1 = metrics.getJSONObject(0);
        JSONArray timeslices = array1.getJSONArray("timeslices");
        JSONObject array2 = timeslices.getJSONObject(0);
        JSONObject values = array2.getJSONObject("values");


        Iterator<String> nameItr = values.keys();
        Map<String, Integer> outMap = new HashMap<String, Integer>();
        while(nameItr.hasNext()) {
            String name = nameItr.next();
            outMap.put(name, values.getInt(name));
            System.out.println(name + ": " + values.getInt(name));
        }

Is there a cleaner way for me to parse this JSON? Stack wants me to add more details

JTK
  • 1,469
  • 2
  • 22
  • 39

1 Answers1

1

I think a much nicer way would be to use e.g. Jackson's ability to deserialize json into a POJO.

I know this is not always feasable especially when your JSON is dynamic. But the case you posted looks like a good candidate.

Have a look here for this hello world example: https://github.com/FasterXML/jackson-databind

POJO:

// Note: can use getters/setters as well; here we just use public fields directly:

    public class MyValue {
      public String name;
      public int age;
      // NOTE: if using getters/setters, can keep fields `protected` or `private`
    }

The object Mapper that does the work for you

ObjectMapper mapper = new ObjectMapper(); // create once, reuse

Converting the JSON to your POJO:

value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);

Hope this helps.

Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70