Search code examples
jsonannotationsjacksonrestletxstream

Restlet XStream/Jackson different JSON wrapper


I would like to switch from Xstream to Jackson for serializing/deserializing objects in a Restlet server. If i use Xstream libraries for:

@Get("json")
public Profile retrieve() {

    Profile prf = new Profile (...);

    ...

    return prf;
}

i would get something like:

{"Profile":{"id": 1, "name": "jack" ... }}

while with Jackson i get only:

{"id": 1, "name": "jack" ... }

How can i get the same JSON with Jackson? i would need this for KVC objects in my client (otherwise i need to specify the mappings manually)

I have the same issue if i return an ArrayList< Profile > , jackson doesn't wrap the list of Profiles when serialized and the JSON instead of

{Profile:[{firstProfile}, {secondProfile}]}

it looks like:

[{firstProfile}, {secondProfile}]

i've also been also trying to use Jackson annotations:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
public class MyProfileServerResource extends ServerResource {

but it seems it's not interpreted by restlet


Solution

  • the correct place for the annotation is in the Profile class:

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
    public class Profile extends Element implements Serializable {
    

    and the json now looks like:

    {"Profile":{ ... }}
    

    and the return type is a Sub-classed list:

    public class ProfileList extends ArrayList<Profile>
    {}
    

    see http://wiki.fasterxml.com/JacksonPolymorphicDeserialization 5.1