解析JSON对象的干净方法 [英] Clean way to Parse JSON object

查看:158
本文介绍了解析JSON对象的干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从服务器中提取一些JSON,然后将其解析并插入到Hashmap<>中:

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

修改 我已经添加了以下JSON响应示例,它将永远不会具有这种结构.

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

我可以使用一种更干净的方法来解析此JSON吗? Stack希望我添加更多详细信息

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

推荐答案

我认为更好的方法是使用杰克逊的能够将json反序列化为POJO.

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

我知道这并不总是可行的,尤其是当您的JSON是动态的时.但是您发布的案例看起来不错.

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

在此处查看此hello world示例: https://github.com/FasterXML/jackson-databind

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

将JSON转换为您的POJO:

Converting the JSON to your POJO:

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

希望这会有所帮助.

这篇关于解析JSON对象的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆