Jersey / Rest default character encoding

前端 未结 3 1052
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 14:15

Jersey seems to fail when returning JSON...
This:

@GET
@Produces( MediaType.APPLICATION_JSON + \";charset=UTF-8\")
public List getMyObje         


        
3条回答
  •  不知归路
    2020-12-16 14:44

    I had the same problem : i don't like adding the charset in the "@Produces" tag everywhere.

    I found the solution right here : http://stephen.genoprime.com/2011/05/29/jersey-charset-in-content-type.html

    Basically, you just have to add a response filter that will add the charset (for example if the content type currently returned is either text, xml or json)

    import com.sun.jersey.spi.container.ContainerRequest;
    import com.sun.jersey.spi.container.ContainerResponse;
    import com.sun.jersey.spi.container.ContainerResponseFilter;
    
    import javax.ws.rs.core.MediaType;
    
    public class CharsetResponseFilter implements ContainerResponseFilter {
    
        public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    
            MediaType contentType = response.getMediaType();
            response.getHttpHeaders().putSingle("Content-Type", contentType.toString() + ";charset=UTF-8");
    
            return response;
        }
    }
    

    And to register the filter :

    ServletAdapter jerseyAdapter = new ServletAdapter();
    jerseyAdapter.addInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", "com.my.package.MyResponseFilter"); 
    

    Works too with Guice, of course, for example in your class extending ServletModule :

    final Map parameters = new HashMap();
    parameters.put("com.sun.jersey.spi.container.ContainerResponseFilters", com.package.JerseyCharsetResponseFilter.class.getName());
    serve("/*").with(GuiceContainer.class, parameters);
    

提交回复
热议问题