java - 在 Jersey 中,如何使某些方法使用 POJO 映射功能而某些方法不使用?

标签 java rest jersey

我有一个资源(这不是必需的),其中有许多不同的 @GET 方法。我已将我的 web.xml 配置为包含此内容:

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

这会打开 POJO mapping feature效果很好。它允许我返回一个 pojo,它会自动转换为 JSON。

问题是我有一些我想重用的代码,它以字符串形式返回 JSON。我在使用这些方法时遇到了问题,因为 Jersey 不会将其解释为 JSON 响应,而是将其解释为 JSON 对象的字符串值。因此,例如,如果返回 String 的方法返回客户端看到的空列表

"[]"

代替

[]

问题是 JSON 包含在双引号中。对于这些返回字符串的方法,我如何告诉 Jersey 按原样返回字符串?

最佳答案

您可能必须使用自定义响应(或请求)映射器。

1.- 创建一个实现 MessageBodyWriter(或 MessageBodyReader)的类,负责编写/读取响应

@Provider
public class MyResponseTypeMapper 
  implements MessageBodyWriter<MyResponseObjectType> {
     @Override
     public boolean isWriteable(final Class<?> type,final Type genericType,
                final Annotation[] annotations,
                final MediaType mediaType) {
       ... use one of the arguments (either the type, an annotation or the MediaType)
           to guess if the object shoud be written with this class
     }
     @Override
     public long getSize(final MyResponseObjectType myObjectTypeInstance,
                     final Class<?> type,final Type genericType,
                         final Annotation[] annotations,
                     final MediaType mediaType) {
        // return the exact response length if you know it... -1 otherwise
        return -1;
    }
    @Override
    public void writeTo(final MyResponseObjectType myObjectTypeInstance,
                    final Class<?> type,final Type genericType,
                    final Annotation[] annotations, 
                    final MediaType mediaType,
                    final MultivaluedMap<String,Object> httpHeaders,
                    final OutputStream entityStream) throws IOException,                                                                 WebApplicationException {
        ... serialize / marshall the MyResponseObjectType instance using
            whatever you like (jaxb, etC)
        entityStream.write(serializedObj.getBytes());
    }
}

2.- 在您的应用中注册映射器

public class MyRESTApp 
     extends Application  {
    @Override
public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(MyResponseTypeMapper.class);
        return s;
    }
}

Jersey 将扫描所有已注册的 Mappers,调用它们的 isWriteable() 方法,直到一个返回 true...如果是这样,这个 MessageBodyWriter 实例将用于将内容序列化到客户端

关于java - 在 Jersey 中,如何使某些方法使用 POJO 映射功能而某些方法不使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801174/

相关文章:

java - Jersey 和 Google App Engine (GAE) 不适合我

http - 如何处理 Jersey 发布请求的可变数量参数

java - 线程 "main"java.lang.NoClassDefFoundError : junit/textui/ResultPrinter 中的异常

java - 智能 GWT 应用程序不显示任何内容,因为找不到 nocache.js 文件错误

java - 动态创建循环以遍历 List<String> 的列表

java - findAll() 在 SpringBoot Rest MySql CRUD 操作应用程序中不起作用

java - NullPointerException 创建自己的 JSON 响应对象

java - JNI 结构对齐

java - 与 Java 进程之间的通信是否仍在微服务中?

java - wadl 文件可以在构建时生成吗?