简体   繁体   中英

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

I have a DTO like this:

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:

{
    "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.

Thanks @fge for putting me on the right track. Jackson has @JsonAnySetter and @JsonAnyGetter annotations that can be used to do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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