9

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.

David Tinker
  • 9,383
  • 9
  • 66
  • 98
  • 2
    Using Jackson's streaming API and a builder class for `Foo`, yes, it is possible. I believe Jackson even has the possibility to swallow "the rest" of unmapped members into a `Map`, however I have never used that... – fge Jun 03 '13 at 19:35
  • you could try gson as well (but it works for draft3 version) – Chris Jun 03 '13 at 19:43
  • @David : I am curious about your use-case demanding that sort of JSON structure. What if `params` had a key with the name `bar` ? – nadirsaghar Jun 03 '13 at 20:55
  • Its part of an API that supports POST of a JSON body or form data. So its helpful if the JSON is flat and the endpoint in question needs to be able to accept extra stuff. And yes it might be a problem if a field matching an existing key in params is added in future. – David Tinker Jun 03 '13 at 21:03
  • Have you tried to use reflection? – Michał Ziober Jun 03 '13 at 21:40

1 Answers1

5

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; }
}
David Tinker
  • 9,383
  • 9
  • 66
  • 98