Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass raw JSON via Jackson?

We have a whole set of JAX-RS REST services running on top of Apache CXF and Jackson. We use JAXB annotations to take care of marshalling POJOs to JSON, works great.

However, we have one or two places where we want to return raw JSON string (that we fetch from a Redis cache).

Jackson always wraps the string in double quotes and escapes all the double quotes in it, e.g.

@GET @Produces("application/json")
public Response getData() {

    String json = ...get from Redis...
    return Response.ok(json,"application/json").build() 
}

gives us

"{\"test\":1}"

instead of

{"test":1}

I've tried multiple things, adding RawSerializer(String.class) to the Object mapper, nothing works. The only thing that works is if I set the media type to plain string, which bypassed Jackson, but is not good, since I am returning the wrong content type

i.e.

return Response.ok(json,"text/plain").build() 

works, but poorly (wrong content type, which screws up .Net WCF apps that call us)

like image 921
Jacek Furmankiewicz Avatar asked May 17 '12 20:05

Jacek Furmankiewicz


1 Answers

Found the solution finally. The trick was to extend the JacksonJsonProvider (which we use in CXF to force it to use Jackson instead of Jettison) and tell it to bypass Jackson altogether when dealing with raw Strings:

public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType){
    if (String.class.equals(type)) {
        //pass strings as-is, they are most likely cached JSON responses
        return false;
    } else {
        return true;
    }
}

Works perfectly.

like image 71
Jacek Furmankiewicz Avatar answered Oct 05 '22 22:10

Jacek Furmankiewicz