杰森要在泽西岛打球

时间:2013-09-11 02:59:06

标签: java jersey dropwizard

我有一个带POST方法的ajax请求。该请求将Json数据发布到服务器。我想将这个json解析为这样的字符串:

 @POST
 @Path("file/save")
 @Consumes(MediaType.APPLICATION_JSON)
 public void save(String content) {
 }

每当我尝试向服务器发出请求时,我都会收到此错误:

“错误400无法从START_OBJECT标记中反序列化java.lang.String的实例”

这是Post请求的详细信息:

Request URL: http://localhost:8181/file/save
Request Method:POST
Status Code:400 Bad Request

Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:379
Content-Type:application/json
Cookie:JSESSIONID=0AFC5FF7F201391DD67CCB0DA1BCD25C
Host:localhost:8181
Origin:http://localhost:8181
Referer:http://localhost:8181
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)    Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest

Query String Parameters

Request Payload
<my json data>

Response Headers
Cache-Control:must-revalidate,no-cache,no-store
Content-Length:1369
Content-Type:text/html;charset=ISO-8859-1
Date:Wed, 11 Sep 2013 03:11:03 GMT
Server:Apache-Coyote/1.1

我该如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

问题在于您的JAX-RS实现(在本例中为Jersey)不知道如何将application/json内容映射到String。您需要注册使用MessageBodyReader<String>注释的@Consumes(MediaType.APPLICATION_JSON)实施。

<强>附录

实施转换为MessageBodyReader的{​​{1}}非常简单。

String

有几种方法可以使用JAX-RS实现注册实体提供程序。使用Jersey可能更容易的方法是将以下内容添加到@Provider @Consumes(MediaType.APPLICATION_JSON) public class JsonStringReader implements MessageBodyReader<String> { @Override public boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {return type == String.class;} @Override public String readFrom( Class<String> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream ) throws IOException, WebApplicationException { final String charsetName = mediaType.getParameters().get(MediaType.CHARSET_PARAMETER); final Charset charset = charsetName == null ? Charset.forName("UTF-8") : Charset.forName(charsetName); final StringBuilder builder = new StringBuilder(); final Reader reader = new InputStreamReader(entityStream, charset); final CharBuffer buffer = CharBuffer.allocate(1024); while (reader.read(buffer) != -1) { buffer.flip(); builder.append(buffer); buffer.clear(); } return builder.toString(); } }

web.xml

有关为Jersey创建实体提供程序的更多信息,请访问:https://jersey.java.net/documentation/latest/message-body-workers.html

有关配置Jersey的更多信息,请访问:http://jersey.java.net/nonav/apidocs/1.8/jersey/com/sun/jersey/spi/container/servlet/ServletContainer.html