根据您上面的代码,您的CSVMessageBodyWriter
正在被调用,但它失败了isWriteable
check.
Your isWriteable
check 总是会返回 false。您正在检查是否JaxbList
可分配自CSVSerializer
。这总是会失败,而你的CSVMessageBodyWriter
将被视为无法处理text/csv
.
尝试将 isWriteable 方法更改为以下内容:
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
return true;
}
这将序列化所有text/csv
带注释的方法。如果你想限制它JaxbList
那么你可以这样做:
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
ParameterizedType paramType = (ParameterizedType) genericType;
if(paramType.getRawType().equals(JaxbList.class))
{
return true;
}
return false;
}
这是配置自定义的简单工作示例MessageBodyWriter
:
应用
public class ProductGuideApplication extends Application
{
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> classes = new HashSet<Class<?>>();
public ProductGuideApplication()
{
singletons.add(new CSVMessageBodyWriter());
classes.add(FooResource.class);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
@Override
public Set<Class<?>> getClasses()
{
return classes;
}
}
Resource
@Path("/foo")
public class FooResource
{
@GET
@Produces("text/csv")
public List<Consumer> getConsumers()
{
Consumer consumer1 = new Consumer();
consumer1.setId("1234");
consumer1.setGender("Male");
Consumer consumer2 = new Consumer();
consumer2.setId("2345");
consumer2.setGender("Male");
List<Consumer> consumers = new ArrayList<Consumer>();
consumers.add(consumer1);
consumers.add(consumer2);
return consumers;
}
}
消息体编写器
@Provider
@Produces("text/csv")
public class CSVMessageBodyWriter implements MessageBodyWriter<List<Consumer>>
{
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
ParameterizedType paramType = (ParameterizedType) genericType;
if(paramType.getRawType().equals(List.class))
{
if(paramType.getActualTypeArguments()[0].equals(Consumer.class))
{
return true;
}
}
return false;
}
@Override
public long getSize(List<Consumer> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
return 0;
}
@Override
public void writeTo(List<Consumer> t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException
{
//Write your CSV to entityStream here.
}
}