users@jersey.java.net

[Jersey] dynamic things, II: map<string,string> <-> JSON?

From: <lists_at_zimmer428.net>
Date: Wed, 13 Apr 2011 10:48:03 +0000 (GMT)

Folks;

playing with "dynamic" stuff again... So far, I found the Object ->
JSON writers in Jersey pretty find when it comes to serializing most of
our object representations, yet again I am running into a situation in
which things are suboptimal: Some of our data objects do contain
(Hash)Map<String,String> properties which need to go to JSON. At the
moment, I did a couple of experiments with this.

- Leaving the HashMap<String,String> in the class definition ends up
with JSON more or less akin to this:

[...]
fields: {
    entry: {
        key: "foo"
        value: "bar"
    }
}
[...]


- Replacing the HashMap<String,String> with an array of "KeyValue" -
Objects does look slightly more convenient yet not completely the way
it should be:

[...]
fields: [
    {
        key: "foo"
        value: "bar"
    }
    {
        key: "blah"
        value: "blubb"
    }
]
[...]

- What I actually want the map to look like in JSON is this:

[...]
fields:
{
   foo : bar,
   blah : blubb
}
[...]

At the moment, there are three ways I can imagine how to do so:

(a) "Tweak" the Jersey / JAXB configuration or the class annotations to
generate the output I want. This would be my favorite approach, yet I
don't know whether this is possible out of the box.

(b) Implement a custom JSONMessageBodyWriter which takes care of doing
this serialization, or re-implement JSON (de)serialization for
HashMap<String,String> objects in my application. Writing the
MessageBodyWriter would need enough effort to work for all the objects
in question (should be doable, but seems not worth the effort as the
"stock" Jersey/JAXB JSON writer works well for most of the objects). I
so far am not aware whether I can override the way JSON is generated
for objects of a certain class only.

(c) Give up on REST methods that return some part of object but return
Response indeed and take care of generating the JSON output desired in
this situation manually with other means. This would be my least
favorable way, somehow.

So, any thoughts on that? How would you eventually address such a use
case?
TIA and all the best,
Kristian