繁体   English   中英

序列化/映射问题Dropwizard / Jersey

[英]Serialization/mapping issue Dropwizard/Jersey

我正在尝试使用我的POJO映射REST调用。 POJO看起来像这样:

public class ResultWrapper implements Serializable{

  private int total;
  private List<Movies> movies; ... getters and setters

在我使用的电话中:

WebResource webResource = client.resource(RequestURI + URLEncoder.encode(movie, "UTF-8"));

ResultWrapper result = webResource.accept("application/json").get(ResultWrapper.class);

错误:

com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class models.ResultWrapper, and Java type class models.ResultWrapper, and MIME media type text/javascript; charset=ISO-8859-1 was not found

客户是泽西岛客户。 我试过从Chrome(Postman)发出呼叫,并且它返回的应用程序类型是“text / javascript”,而不是“application / json”,正如人们所期望的那样? 我认为这将是我的问题。

有没有什么方法可以让ObjectMapper解决它实际上是“application / json”而不是“text / javascript”。 我已经尝试使用String.class然后我得到了Json对象就好了。

我的目的是使用Jersey客户端的自动映射。

感谢您的任何提示或建议。

尝试添加注释@Produces (MediaType.APPLICATION_JSON )

你可以试试这个:

@Provider
@Produces(application/json)
public class YourTestBodyWriter implements MessageBodyWriter<ResultWrapper> {

    private static final Logger LOG = LoggerFactory.getLogger(YourTestBodyWriter.class);

    @Override
    public boolean isWriteable(
        Class<?> type,
        Type genericType,
        Annotation[] annotations,
        MediaType mediaType)
    {
        return ResultWrapper.class.isAssignableFrom(type);
    }

    @Override
    public long getSize(
        ResultWrapper t,
        Class<?> type,
        Type genericType,
        Annotation[] annotations,
        MediaType mediaType)
    {
        return -1;
    }

    @Override
    public void writeTo(
        ResultWrapper t,
        Class<?> type,
        Type genericType,
        Annotation[] annotations,
        MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException, WebApplicationException
    {
        String message = t.someMethod()
        entityStream.write(message.getBytes(Charsets.UTF_8));
        LOG.info(message);
    }

}

添加你的应用程序run():

// Serializer
environment.jersey().register(new YourTestBodyWriter ());   

这是你的应用程序的正常方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM