users@jersey.java.net

[Jersey] Re: Get JSON as plain string

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Fri, 11 Feb 2011 10:47:50 -0800

2011/2/11 Arseni Grigorjev <arsenikum_at_gmail.com>:
> Hi,
>
> I have problems figuring out how to dig out a plain JSON string from a
> request.
>
> We're currently using Jersey 1.5.1 + Spring for handling JSON requests, and
> the request structure looks something like this:
>
> {
>   "id": 34324242,
>   "foo": "bar",
>   "info": {
>      "infofield1": "some value",
>      "infofield2": "some other value",
>      "infodetails": {
>        "details1": "aaaa",
>        "details2": "bbbb"
>      }
>   }
> }
>
> The Java class to which this request would map (ideally) looks like this:
>
> @XmlRootElement
> public class FooBarRequest {
>
>     public Integer id;
>
>     public String foo;
>
>     public String infoJson;
> }
>
> The idea is, that we want to get "info" as plain json string (not parsed to
> a any java object structure) to store it directly to DB as a BLOB. This
> doesn't seem to work out-of-a-box for Jersey 1.5.1, we are currently trying
> to upgrade to Jersey version 1.6, but maybe you have some tips on how to do
> that?

This typically does not work: XML and JSON parsers parse contents, and
there is seldom any way to ask them not to parse some section.
So what is then done is to parse into something, re-serialize into
desired format. This is extra work, but is the most straight-forward
way to do it.

Alternative if you do not want to parse, re-serialize, what you can do
is "double-encode", such that you basically embed a JSON or XML
payload as String (properly encoded using XML or JSON encoding; i.e.
give serialized XML/JSON document as String value to encode); and then
store "String" as a BLOB.
This is quite commonly used for payload, and has its benefits and drawbacks.

Hope this helps,

-+ Tatu +-