如何使用杰克逊获得json响应?

时间:2016-07-21 17:15:45

标签: java jackson objectmapper

我是杰克逊的新手,我有一个示例json输出需要使用jackson来获取这些数据作为响应,我已经创建了pojo类,因为我知道这种问题要通过json简单实现,但是我没有想到要用杰克逊做这件事。请一些人提供一些帮助。

这是我的样本json数据 -

{
"apmmetrics": [
    {
        "metric": "Somevalue",
        "level": "somevalue",
        "data": [
            {
                "host": "someValue",
                "instance": "someValue",
                "app": "someValue",
                "series": [
                    {
                        "bucket": "201607210949",
                        "max": 300,
                        "min": 15,
                        "avg": 57.55,
                        "total": 1899,
                        "count": 33
                    },
                    {
                        "bucket": "201607210948",
                        "max": 437,
                        "min": 13,
                        "avg": 93.5,
                        "total": 13464,
                        "count": 144
                    },
                    {
                        "bucket": "201607210947",
                        "max": 431,
                        "min": 13,
                        "avg": 86.25,
                        "total": 28376,
                        "count": 329
                    }
                ]
            }
        ]
    }
]}

这些是我的pojo课程 -

public class MetricsCollection {

private String metric;
private String level;
private List<MetricsGroup> data;
private transient Map<String, MetricsGroup> meta;

}

public class MetricsGroup {

private String host;
private String instance;
private String app;
private List<GenericMetrics> series;
private transient Map<String, GenericMetrics> metaMap;
}


public class BaseMetrics implements Serializable {
private static final long serialVersionUID = -3249688349785265214L;
protected double max = 0.0;
protected double min = 0.0;
protected double avg = 0.0;
protected double total = 0.0;
protected long count = 0;
}


public class GenericMetrics extends BaseMetrics {

private static final long serialVersionUID = -9057601499394607167L;
private String bucket;
private transient long rc = 0;

}

请让我知道如何实现这一目标。真的很感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您应该使用名为apmmetrics MetricsCollection的属性数组创建另一个类(rootPojo)。 然后生成json:mapper.writeValueAsString(rootPojo);

编辑:

或者只是:

final ObjectMapper mapper = new ObjectMapper();
final Map<String, List<MetricsCollection>> dataMap = ...
dataMap.put("apmmetrics", listOfMetricsCollection);
System.out.println(mapper.writeValueAsString(dataMap));