users@jersey.java.net

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

From: Kristian Rink <lists_at_zimmer428.net>
Date: Thu, 14 Apr 2011 08:22:59 +0200

Tatu;

first off, thanks a bunch for your reply and comments, much
appreciated. :)

Am Wed, 13 Apr 2011 15:14:08 -0700
schrieb Tatu Saloranta <tsaloranta_at_gmail.com>:
> For JSON, using Jackson-based POJO mapping Maps should come out
> looking as Maps, which is what you want.
>
> Challenge with other approaches that go via JAXB conversions is that
> since XML does not have natural representation for Maps (compared to
> JSON), additional levels are added to preserve ability to do
> round-tripping to/from XML.

Yes, I almost expected this. However, in the meantime I also did play
around a little with things and stumbled across the svenson JSON
library [1] (which I happen to use in all situations in which to play
with CouchDB). In the end, in case anyone is interested, the final
solution in my case uses a MessageBodyWriter that renders text/html
output and a svenson based method writing out JSON output. Even though
this probably leaves a lot of room to be made more beautiful or
efficient, it works like a charm (and again leaves me amazed looking at
how smooth things are in Jersey... ;) ):


[...]
    @GET
    @Path("{id}")
    @Produces("application/json")
    public Response getFoo(@PathParam("id") String id) {
        return
    Response.ok(JSON.defaultJSON().forValue(this.getFooHtml(id)),
    "application/json").build(); }

    @GET
    @Path("{id}")
    @Produces("text/html")
    public Foo getFooHtml(@PathParam("id") String id) {
        final Foo f = this.getFromDb(id);

        if (null == f) {
            throw new NotFoundException();
        }

        return f;
    }
[...]


Cheers,
Kristian


[1] http://code.google.com/p/svenson/