无法从Jersey REST Web服务向Ajax发送JSON对象

时间:2016-07-28 09:52:35

标签: java json ajax rest jersey

我正在编写一个简单的Jersey REST Web服务,我在这里使用JSON对象并发送另一个JSON对象。这只是解决方法。它会引发以下错误。

org.codehaus.jackson.map.JsonMappingException:没有为类org.json.JSONObject找到序列化程序,也没有发现创建BeanSerializer的属性(为了避免异常,请禁用SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS))

Ajax代码

        $('#click').click(function() {
        $.ajax({
            url: "http://localhost:8080/test/rest/myService/jsonpost",
            method: "POST",
            data: jsonObj,
            dataType: 'application/json',
            contentType: "application/json",
             success: function(result){
                  alert(result);
             },
             error(){
                 alert("error");
                 console.log('Error');
             }
        });

    });

我的代码是:

@POST
@Path("/jsonpost")
@Consumes(MediaType.APPLICATION_JSON)
//@Produces(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON })
public Response consumeJSON( Track track ) {

    System.out.println("In post example");
    String output = track.toString();
    System.out.println("Post data"+output);
    JSONObject obj = new JSONObject();
    obj.put("1", "Shane");
    obj.put("2", "Bond");
    System.out.println(obj);

    return Response.status(200).entity(obj.toString()).build();
    //return Response.status(200).entity("success").build();
}

整个错误日志

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.failForEmpty(StdSerializerProvider.java:90)
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:63)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:587)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:245)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1145)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:520)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

2 个答案:

答案 0 :(得分:1)

如果使用org.codehaus.jackson.map.ObjectMapper,请在代码中使用以下行。

mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

答案 1 :(得分:0)

杰克逊打算与POJO一起使用(比如你的Track课程)。它不了解或如何序列化这些org.json对象。我建议只使用POJO。使用明确定义域的域类,应用程序将更易于维护。

话虽如此,仍然可以使它与org.json对象或任意键/值集合一起使用。

  1. 您可以简单地返回String而不是JSONObject

    return Response.ok(obj.toString());
    
  2. 您可以改用Map<String, String>。杰克逊知道如何序列化这些。

  3. 有一个support module for org.json,但它仅适用于Jackson 2.x(com.fasterxml而不是org.codehaus)

    如果您想使用Jackson 2.x,可以查看this post。然后,您需要注册前面链接中显示的JsonOrgModule。您可以在ContextResolver中执行此操作,如this post中所示。走这条路,这是你的清单

    • 确保你拥有Jackson 2的依赖。
    • 确保您使用Jersey
    • 注册Jackson套餐
    • 删除较旧的杰克逊依赖
    • 实施注册ContextResolver的{​​{1}}。这将允许杰克逊了解JsonOrgModule对象。
  4. 如果您需要有关配置最后一个选项的帮助,请使用您的web.xml和依赖项更新您的帖子