将JSON响应解析为List

时间:2015-10-25 22:32:48

标签: java json

我试图解析JSON响应

它的结构是:

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

到目前为止我的代码:

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

我得到的输出是说&#34;值&#34;没找到,

我是否误解了JSON响应的结构?

修改

似乎我在网站上给出的结构我收到的回复是不正确的。它似乎是一个更复杂的结构

我已相应修改了我的代码:

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

打印输出如下:

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

阵列中似乎有另一个数组:&#34; timeslices&#34;是对的吗?我怎么得到那个阵列?

我没试成功:

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

1 个答案:

答案 0 :(得分:2)

valuesmetric内的字段。

您需要先获取metric对象,然后查看values内的对象。

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