我有一个资源(这不是必需的),其中有许多不同的@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作为String返回。我在使用这些方法时遇到了麻烦,因为Jersey不会将此解释为JSON响应,而是将其解释为JSON对象的String值。因此,例如,如果返回String的方法返回客户端看到的空列表
"[]"
而不是
[]
问题是JSON包含在双引号中。对于返回字符串的这些方法,我如何告诉Jersey按原样返回字符串?
答案 0 :(得分:2)
您可能需要使用自定义响应(或请求)映射器。
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.-在您的应用中注册Mappers
public class MyRESTApp
extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(MyResponseTypeMapper.class);
return s;
}
}
Jersey将扫描所有已注册的Mapper,调用其isWriteable()方法,直到返回true ...如果是,则此MessageBodyWriter实例将用于将内容序列化到客户端