本文介绍了如何使用jackson在java中解包和序列化java地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的bean

class Foo {
    private Map<String, Data> dataMap;
    private String fooFieldOne;
    private String fooFieldTwo;
}

class Data {
    private fieldOne;
    private fieldTwo;
}

我想像Json一样序列化

I want to serialize as Json as like this

{
    "key1": {
        "fieldOne": "some value",
        "fieldTwo": "some value"
    },
    "key2": {
        "fieldOne": "some other value",
        "fieldTwo": "some other value"
    },
    "fooFieldOne":"valueone", 
    "fooFieldTwo":"valuetwo" 
}

但我得到的结果如

{
    "dataMap": {
        "key1": {
            "fieldOne": "some value",
            "fieldTwo": "some value"
        },
        "key2": {
            "fieldOne": "some other value",
            "fieldTwo": "some other value"
        }
    },
    "fooFieldOne":"valueone", 
    "fooFieldTwo":"valuetwo" 
}

如何忽略上面json中的dataMap图层?我正在使用java jackson库。

How to ignore dataMap layer in the above json? I'm using java jackson library for this.

我试过的代码是

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(myFOOObject)


推荐答案

你可以为 dataMap 创建一个getter并序列化 dataMap 而不是整个 Foo 实例。

You could create a getter for dataMap and serialize the dataMap instead of the entire Foo instance.

mapper.writeValueAsString(myFOOObject.getDataMap());

另一种方法是使用 @JsonUnwrapped 注释。这个注释在Jackson 1.9 +中可用。

Another method is using the @JsonUnwrapped annotation. This annotation is available in Jackson 1.9+.

使用此注释的缺点是无法使用

The downside of using this annotation is the inability to use maps as stated in the answer to your other question

这篇关于如何使用jackson在java中解包和序列化java地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:49