Annotating a resource to create JSON, but returning "text / plain" in the response header

I am currently implementing a web API

The output (if any) will be JSON, so all my classes are annotated with the expected media type.

@Produces(MediaType.APPLICATION_JSON) public class CustomerResource { ... } 

this way my classes are automatically converted to json.

BUT...

Due to Microsoft, their IE only supports CORS if the request / response type is text / open http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and- workarounds.aspx

 4. Only text/plain is supported for the request Content-Type header 

so I need to make the application react with the / plain text in the header, but still project my classes to json output. I know that the CORS classes that I added set this header, but for some reason it is overwritten by my annotation again, even if I add another filter myself.

+6
source share
1 answer

Hum, the link you provide says that this is true only for REQUESTS . This way you can only accept text images, but they can freely create what you want.

EDIT Try registering a custom response filter with code like this (maybe you already did this?):

 @Provider public class HeaderRewriteFilter implements ContainerResponseFilter { @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { response.setResponse(Response .fromResponse(response.getResponse()).header(HttpHeaders.CONTENT_TYPE, "text/plain").build()); return response; } } 

However, check the result to make sure that this is normal if the response already contains this header. Otherwise, you can try to change the current answer, but I'm not sure what you can, as it could be an immutable object. And by the way, it looks less clean to me :)

 List<Object> contentTypes = response.getHttpHeaders().get(HttpHeaders.CONTENT_TYPE); contentTypes.clear(); contentTypes.add("text/plain"); 

Also to create json <> java databiding you can check the Genson library http://code.google.com/p/genson/ , it goes well with Jersey. Just lower the can into the classroom path and run!

EDIT 2 OK, then you have to do it differently, use the "text / plain" command and define a jquery bodywriter for this type. The downside is that you can only create json. With Genson, you could do this:

 @Provider @Produces({ MediaType.TEXT_PLAIN }) public class PlainTextJsonConverter extends GensonJsonConverter { public GensonJsonConverter() { super(); } public GensonJsonConverter(@javax.ws.rs.core.Context Providers providers) { super(providers); } } 
+2
source

All Articles