简体   繁体   English

是否可以将JSON序列化/反序列化为Java DTO,并将额外的字段放入映射中?

[英]Is it possible to serialize/deserialize JSON to Java DTO with extra fields going into a map?

I have a DTO like this: 我有这样的DTO:

public Foo {
    public int bar = 123;
    public Map<String, Object> params; // key1=v1, key2=v2 etc.
}

I would like it to serialize to/from the following JSON: 我希望它能够序列化到以下JSON:

{
    "bar": 123,
    "key1": "v1",
    "key2": "v2"
} 

Does anyone know how to do this using Jackson or Genson? 有没有人知道如何使用杰克逊或简森这样做? Basically I want automatic type conversions for the fields declared in the DTO but any "extras" to go into the params map. 基本上我想要在DTO中声明的字段进行自动类型转换,但是任何“额外”都要进入参数映射。

Thanks @fge for putting me on the right track. 谢谢@fge让我走上正轨。 Jackson has @JsonAnySetter and @JsonAnyGetter annotations that can be used to do this: Jackson有@JsonAnySetter和@JsonAnyGetter注释可用于执行此操作:

public Foo {
    public int bar;
    private transient Map<String, Object> params = new HashMap<String, Object>();

    @JsonAnySetter
    public void set(String k, Object v) { params.put(k, v); }

    @JsonAnyGetter
    public Map getParams() { return params; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM