如何使用 jackson 获得 json 响应?

How to get a json response using jackson?

我是 jackson 的新手,我有一个示例 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;

}

请告诉我如何实现。真的会很感激。提前致谢。

您应该创建另一个 class (rootPojo),其属性数组名为 apmmetrics of MetricsCollection。 然后生成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));