users@jersey.java.net

[Jersey] Re: JSON inside POJO

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Wed, 17 Aug 2011 22:32:59 -0700

On Wed, Aug 17, 2011 at 3:29 PM, Pierre Radermecker
<pradermecker_at_yahoo.ca> wrote:
> Hi,
> I have a serialization problem using Jersey 1.8.
>
> I have a POJO that have one JSONObject attribute. The complete POJO needs to
> be serialized as JSON:
>
> @XmlRootElement(name = "location")
> public class Pojo implements Serializable {
>     @XmlElement
>     String name;
>     @XmlElement
>     JSONObject input;
>     }
> }
> I receive the JSON input from another source (stream of bytes) and just need
> to use it (with no conversion)
>
> The attribute "JSONObject" does not do what I want. If I use plain JAXB, I
> have got a null as the "input" value. If I set the property:
> "com.sun.jersey.api.json.POJOMappingFeature" to true, I have a error saying
> there is no Serializer for JSONObject.

Problem with the last one is that JSONObject is a type of org.json
library (not part of JDK but provided by a third-party library), and
hence Jackson (library used when POJOMappingFeature is enabled) does
not recognize it by default.
However, there is an extension module available,
[https://github.com/FasterXML/jackson-module-json-org] which will add
full conversion support, meaning that your use case should just work.

To register this module, you need to be able to provide ObjectMapper
for Jersey to use; usually this is done by registering
Provider<ObjectMapper>, although there are other ways as well.

Other than this, do you really need to handle things as JSONObject?
This may be the case if you are calling another library that takes
JSONObject input; but if not, there isn't necessarily point in doing
that.
You could just rather bind to simple Map<String,Object>, which is more
general (or, if you want a decent tree model, to JsonNode provided by
Jackson)

Hope this helps,

-+ Tatu +-