Java 在Jersey中,如何使一些方法使用POJO映射特性,而另一些方法不使用POJO映射特性?
我有一个资源(这不是一个需求),其中有许多不同的Java 在Jersey中,如何使一些方法使用POJO映射特性,而另一些方法不使用POJO映射特性?,java,rest,jersey,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> 而不是 [] 问题
@GET
方法。我已将web.xml配置为包含以下内容:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
而不是
[]
问题是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());
}
}
@Provider
公共类MyResponseyPemapper
实现MessageBodyWriter{
@凌驾
公共布尔值可写(最终类类型、最终类型genericType、,
最终注释[]注释,
最终媒体类型(媒体类型){
…使用其中一个参数(类型、注释或MediaType)
猜测是否应该使用此类编写对象
}
@凌驾
公共长getSize(最终MyResponseObjectType myObjectTypeInstance,
最终类类型,最终类型genericType,
最终注释[]注释,
最终媒体类型(媒体类型){
//如果您知道,请返回准确的响应长度…-1,否则返回
返回-1;
}
@凌驾
公共无效写入(最终MyResponseObjectType myObjectTypeInstance,
最终类类型,最终类型genericType,
最终注释[]注释,
最终MediaType MediaType,
最终多值MAP HttpHeader,
最终输出流(entityStream)引发IOException、WebApplicationException{
…使用
你喜欢什么(jaxb等)
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;
}
}
公共类MyRESTApp
扩展应用程序{
@凌驾
public Set>s=新哈希集
public class MyRESTApp
extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(MyResponseTypeMapper.class);
return s;
}
}