0

我有一个带有 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

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

4

1 回答 1

1

问题是您的 JAX-RS 实现(在本例中为泽西岛)不知道如何将application/json内容映射到String. 您需要注册一个MessageBodyReader<String>带有注释的实现@Consumes(MediaType.APPLICATION_JSON)

附录

实现MessageBodyReader转换为的 aString很简单。

@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();
   }
}

有几种方法可以向 JAX-RS 实现注册实体提供者。使用 Jersey 可能更容易的方法是将以下内容添加到您的web.xml:

<init-param>
   <param-name>com.sun.jersey.config.property.packages</param-name>
   <param-value>pkg.that.contains.the.messagereader</param-value>
</init-param>

可以在此处找到有关为泽西岛创建实体提供程序的更多信息: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

于 2013-09-11T06:13:29.220 回答