JTK
JTK

Reputation: 1519

Parse JSON response into a List

I'm trying to parse a JSON response

it's structure is:

{
  "metric": {
    "name": "string",
    "values": [
      "string"
    ]
  }
}

My code so far:

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

        JSONObject json = new JSONObject(sb.toString());
        JSONArray jsonArray = json.getJSONArray("values");
        List<String> list = new ArrayList<>();
        String errorPercent ="";

        for(int i = 0 ; i < json.length() ; i++){
            errorPercent = jsonArray.getJSONArray(i).getString(i);
            list.add(errorPercent);
        }

The output I'm getting is saying that "values " was not found,

am I misunderstanding the structure of the JSON response?

Edit

It appears the structure I was given on the site I'm receiving the response from is not correct. it appears to be a more complicated structure

I have modified my code accordingly:

            JSONObject json = new JSONObject(sb.toString());
            JSONObject metricsData = json.getJSONObject("metric_data");
            JSONArray metrics = metricsData.getJSONArray("metrics");
            System.out.println(metrics.toString());

The print out is as follows:

[{"timeslices":[{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},"from":"2015-10-25T22:39:00+00:00","to":"2015-10-25T22:40:00+00:00"},{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},

There appears to be another array within the array: "timeslices" is that right? how do I get at that array?

I unsuccessfully tried:

JSONArray timeslices = metrics.getJSONArray("timeslices");

Upvotes: 0

Views: 1972

Answers (1)

Andy Turner
Andy Turner

Reputation: 140299

values is a field inside metric.

You'd need to first get the metric object, then look inside that for values.

JSONObject metric = json.getJSONObject("metric");
JSONArray jsonArray = metric.getJSONArray("values");

Upvotes: 2

Related Questions