简体   繁体   English

Jersey Restful Web服务 - MessageBodyProviderNotFoundException

[英]Jersey Restful Web Service - MessageBodyProviderNotFoundException

I'm new to Java Web Services and I'm struggling with a basic problem. 我是Java Web Services的新手,我正在努力解决一个基本问题。

After finding a bunch of outdated examples I managed to get something working with XML however the same code wont work when I ask it to return JSON. 在找到一堆过时的例子之后,我设法得到了一些使用XML的东西,但是当我要求它返回JSON时,相同的代码不会工作。

Initially I thought it was a missing JSON formatter but JAXB should be taking care of the conversion from POJO to JSON so I don't believe that's the problem. 最初我认为它是一个缺少的JSON格式化程序,但JAXB应该处理从POJO到JSON的转换,所以我不相信这是问题所在。

The error being thrown within Tomcat is: 在Tomcat中抛出的错误是:

javax.servlet.ServletException: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class resttest.model.Todo, genericType=class resttest.model.Todo

WEB.XML WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">
  <display-name>testtest</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>        
      <param-value>resttest.jaxb;resttest.model</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app> 

Todo.java Todo.java

package resttest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Todo {

    public Todo(){};

  private String summary;
  private String description;

  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  } 
}

TodoResource.Java TodoResource.Java

package resttest.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import resttest.model.Todo;

@Path("/todo")
public class TodoResource {

  @GET
  @Produces("application/json")
  public Todo getTodo() {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo");
    todo.setDescription("This is my first todo");
    return todo;
  }

} 

Any ideas why the JSON isn't being returned and the error thrown? 任何想法为什么没有返回JSON并抛出错误?

I searched a lot of the responses myself and this is what I ended up doing. 我自己搜索了很多回复,这就是我最终做的事情。 In addition to your TodoResource class, you need a class that extends Application, and class such as the MOXyJsonContextResolver class below to implement the ContextResolver interface. 除了TodoResource类之外,还需要一个扩展Application的类,以及下面的MOXyJsonContextResolver类等类来实现ContextResolver接口。 These help define the Jersey context along with a selected Json converter and optional customizations to the Json output. 这些有助于定义Jersey上下文以及选定的Json转换器和Json输出的可选自定义。 Put the classes in the same package as your resource class and Jersey will find it. 将类放在与资源类相同的包中,Jersey会找到它。 MOXy is now the default for Jersey (I use 2.5.1) and the only json converter that I could get working without receiving your error. MOXy现在是Jersey(我使用2.5.1)的默认设置,也是唯一可以在没有收到错误的情况下工作的json转换器。 Also, make sure you have the MOXy jar included in your build or maven pom.xml (jersey-media-moxy-2.5.1.jar). 此外,请确保您的构建或maven pom.xml(jersey-media-moxy-2.5.1.jar)中包含MOXy jar。

Note: nothing is in my application's web.xml. 注意:我的应用程序的web.xml中没有任何内容。 That was in the older documentation examples and not needed as of Jersey 2.5.1. 那是在较旧的文档示例中,从Jersey 2.5.1开始不需要。

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {

public ApplicationConfig() {
    this.initMethods();
}

@Override
public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
    addRestResourceClasses(resources);
    return resources;
}

private void initMethods() {
    try {
        ...some classes you might need instantiated, etc, for your resource class
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void addRestResourceClasses(Set<Class<?>> resources) {
    resources.add(MOXyJsonContextResolver.class);
}

}

And here is the MOXyJsonContextResolver.class that I used to customize the Json response: 这是我用来自定义Json响应的MOXyJsonContextResolver.class:

public class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig>  {
private final MoxyJsonConfig config;

public MOXyJsonContextResolver() {

    config = new MoxyJsonConfig()
            .setAttributePrefix("")
            .setValueWrapper("value")
            .property(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
}

@Override
public MoxyJsonConfig getContext(Class<?> objectType) {
    return config;
}
}

You forgot to add the attribute: @XmlAccessorType(XmlAccessType.FIELD) 您忘了添加属性: @XmlAccessorType(XmlAccessType.FIELD)

Example: @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Todo { ... 示例: @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Todo { ...

You have mentioned @XmlRootElement at class level in todo class. 你在todo类的类级别提到了@XmlRootElement @XmlRootElement is only required if you want to produce your response in xml format, and also provide @Path at method level in TodoResource class, its a good practice. @XmlRootElement如果要产生你的回应时,才需要xml格式,同时还提供@Path在方法层面TodoResource类,它是一个很好的做法。 mention @Produces(MediaType.APPLICATION_JSON) at method level. 在方法级别提及@Produces(MediaType.APPLICATION_JSON) Hope this will work for you! 希望这对你有用!

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

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