清理Parse JSON对象的方法

时间:2015-10-29 21:51:30

标签: java json parsing

我从服务器上取下一些JSON,我正在解析它并插入Hashmap<>

修改 我已经添加了一个JSON响应示例,它不会总是有这种结构。

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
        }

爪哇:

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

我有更简洁的方法来解析这个JSON吗? Stack希望我添加更多细节

1 个答案:

答案 0 :(得分:0)

我认为更好的方法是使用例如Jackson's能够将json反序列化为POJO。

我知道这并不总是可行的,特别是当你的JSON是动态的时候。但你发布的案例看起来很合适。

看看这个hello world示例: https://github.com/FasterXML/jackson-databind

POJO:

SQL Server 2005+

为您完成工作的对象Mapper

// 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`
    }

将JSON转换为POJO:

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

希望这有帮助。