1

I am using a jackson provider for my rest service:

<jaxrs:server id="services" address="/">
    <jaxrs:serviceBeans>
        <bean class="..."/>
    </jaxrs:serviceBeans>

    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
    </jaxrs:providers>
</jaxrs:server>

I have this class:

public class Response {
    private Date myDate;
    private DataObject data; //data related to that date
}

and this method returning a json:

@Produces("application/json")
public Response getResp(){
       Response r = ...
       return r;
}

This translates in the following json object

{
   "myDate":"20150730",
   "data":{
         "p1":"v1",
         "p2":"v2"
          }
}

Is it possible to obtain something like this, instead:

"20150730":{
         "p1":"v1",
         "p2":"v2"
          }

in other words to have the myDate content to be the actual json property and data content to be the json value?

1 Answer 1

2

You could write your own serializer. For example

import java.io.IOException;
import java.text.SimpleDateFormat;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class ResponseSerializer extends JsonSerializer<Response> {

    @Override
    public void serialize(Response resp, JsonGenerator jg, SerializerProvider sp) 
            throws IOException, JsonProcessingException {
        jg.writeStartObject();
        String dateString = new SimpleDateFormat("yyyyMMdd").format(resp.myDate);
        jg.writeObjectField(dateString, resp.data);
        jg.writeEndObject();
    } 
}

I don't know what your Date object is. I assumed it java.util.Date so I just created a formatter. All this serializer does is add the date string as the key and ObjectData and the value.

Then you need to register the serializer with the ObjectMapper. You can do that in a ContextResolver (which is a JAX-RS way to configure the mapper)

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper>{

    private final ObjectMapper mapper;

    public ObjectMapperContextResolver() {
        mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule(
                "ResponseModule", new Version(1, 0, 0, null)
        );
        module.addSerializer(Response.class, new ResponseSerializer());
        mapper.registerModule(module);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }
}

Then just register the ObjectMapperContextResolver like you would any other provider in your xml config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.