Java 尝试通过 JAX-RS Web 服务发送 JSON 对象时获取“未找到 Media type=application/json 的 MessageBodyWriter”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20762109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:08:29  来源:igfitidea点击:

Obtaining "MessageBodyWriter not found for media type=application/json" trying to send JSON object through JAX-RS web service

javajsonweb-servicesrestjax-rs

提问by amedeo avogadro

I am trying to send a JSON object through a JAX-RS web service. My file web.xml is:

我正在尝试通过 JAX-RS Web 服务发送 JSON 对象。我的文件 web.xml 是:

<servlet>
 <description>JAX-RS Tools Generated - Do not modify</description>
 <servlet-name>JAX-RS Servlet</servlet-name>
 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>it.notifire</param-value>
  </init-param>
  <init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>JAX-RS Servlet</servlet-name>
  <url-pattern>/jaxrs/*</url-pattern>
</servlet-mapping>

The class that models the object I want to send is:

模拟我要发送的对象的类是:

public class GPSCoordinate {

private float latitudine;
private float longitudine;

 public float getLatitudine() {
    return latitudine;
}
public void setLatitudine(float latitudine) {
     this.latitudine = latitudine;
}
public float getLongitudine() {
    return longitudine;
}
public void setLongitudine(float longitudine) {
    this.longitudine = longitudine;
}
}

The root class resource is:

根类资源是:

@Path("position")
public class Position {

    @Context
private UriInfo context;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public GPSCoordinate getHTML() {

        GPSCoordinate coord = new GPSCoordinate();
        coord.setLatitudine(90.45f);
        coord.setLongitudine(34.56f);

        return coord;
    }
}

Now, when i try to access the service I point my browser to the following link

现在,当我尝试访问该服务时,我将浏览器指向以下链接

http://localhost:8080/Notifire/jaxrs/position

and i get the following error:

我收到以下错误:

message org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json

消息 org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:未找到 Media type=application/json 的 MessageBodyWriter

In my WEB-INF/lib folder I have the last release of jersey JAX-RS implementation (jaxrs-ri-2.5.jar) and the jersey-json.jar archive.

在我的 WEB-INF/lib 文件夹中,我有最新版本的 jersey JAX-RS 实现 (jaxrs-ri-2.5.jar) 和 jersey-json.jar 存档。

Any help would be much appreciated.

任何帮助将非常感激。

采纳答案by eugen

Try adding Gensonto your classpath, it will automatically enable JSON support.

尝试将Genson添加到您的类路径中,它会自动启用 JSON 支持。

Genson is a data-binding and streaming library for json and java/scala. It implements the extension points MessageBodyReader/Writer of JAX-RS, allowing jersey to automatically detect Genson and use it for Json parsing/writing.

Genson 是一个用于 json 和 java/scala 的数据绑定和流媒体库。它实现了 JAX-RS 的 MessageBodyReader/Writer 扩展点,允许 jersey 自动检测 Genson 并将其用于 Json 解析/写入。

You can find some more infos about Gensons integration with JaxRS(jersey & cie).

您可以找到有关Gensons 与 JaxRS(球衣和 cie)集成的更多信息。

回答by bickster

This is how I solved the issue.

这就是我解决问题的方法。

Used Hymanson. Added these jars enter image description here

用过Hyman逊。添加了这些罐子 在此处输入图片说明

Added this Class to my project. The key lines of the code are marked IMPORTANT.

将此类添加到我的项目中。代码的关键行被标记为重要的。

import com.fasterxml.Hymanson.jaxrs.json.HymansonJsonProvider; <-- IMPORTANT
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

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

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

@Override
public Set<Object> getSingletons() {
    final Set<Object> instances = new HashSet<Object>();

    instances.add(new HymansonJsonProvider()); <--------- IMPORTANT
    return instances;
}
/**
 * Do not modify addRestResourceClasses() method.
 * It is automatically populated with
 * all resources defined in the project.
 * If required, comment out calling this method in getClasses().
 */
private void addRestResourceClasses(Set<Class<?>> resources) {
    //resources.add(org.glassfish.jersey.media.multipart.MultiPartProperties.Feature.MultiPartContextResolver.class);
    //resources.add(org.glassfish.jersey.media.multipart.MultiPartProperties.Feature.MultiPartContextResolver.class);

}

}

回答by kostja

Jersey supports 'autodiscoverable' features and JSON support is one of them. In order to enable it, you need to add a compatible library to your path, according to the docs

Jersey 支持“自动发现”功能,JSON 支持就是其中之一。根据文档,为了启用它,您需要将兼容的库添加到您的路径中

However, while the recommended jersey-media-json-processinglibrary has not been recognized in my case for some reason, jersey-media-moxyhas:

但是,虽然由于jersey-media-json-processing某种原因在我的案例中没有识别推荐的库,但jersey-media-moxy具有:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.15</version>
</dependency>

2.15 has been the latest version at the time of writing. Visit the maven central artifact pageto find the current version.

在撰写本文时,2.15 是最新版本。访问Maven 中央工件页面以查找当前版本。

回答by Rod SolPar

Go to https://jersey.java.net/documentation/2.5.1/user-guide.html#json

转到https://jersey.java.net/documentation/2.5.1/user-guide.html#json

You need to complete your Class.... JAXB needs that, example:

你需要完成你的类.... JAXB 需要,例如:

@XmlRootElement
public class MyJaxbBean {

    @XmlElement(name="king")
    public String name;

    @XmlTransient
    public int age;

    // several lines removed
}

回答by jFrenetic

My root cause was slightly different. I spent some time debugging Jersey source code, and it turned out that it fails to construct a JAXBContextdue to missing default constructor in my JAXB class. It happens during the search for a suitable MessageBodyWriter, but the exception is not handled.

我的根本原因略有不同。我花了一些时间调试 Jersey 源代码,结果发现JAXBContext由于我的 JAXB 类中缺少默认构造函数,它无法构造 a 。它发生在搜索合适的 MessageBodyWriter 期间,但不处理异常。

Here is the corresponding code snippet (MOXyJsonProvider:324):

这是相应的代码片段 (MOXyJsonProvider:324):

try {
    Set<Class<?>> domainClasses = getDomainClasses(genericType);
    return getJAXBContext(domainClasses, annotations, mediaType, null);
} catch(JAXBException e) {
    return null;
}

So, if you have the Moxy JSON dependency in POM, double-check that your JAXB classes are valid.

因此,如果您在 POM 中有 Moxy JSON 依赖项,请仔细检查您的 JAXB 类是否有效。

Versions that I'm using: Jersey 2.19, Moxy 2.6.0.

我使用的版本:Jersey 2.19、Moxy 2.6.0。

回答by lakshmanas

Register the HymansonJsonProvier class with the client config and then create the Client object, this worked for me. Below is the code.

使用客户端配置注册 HymansonJsonProvier 类,然后创建 Client 对象,这对我有用。下面是代码。

    ClientConfig config = new ClientConfig();
    config.register(HymansonJsonProvider.class);
    Client client = ClientBuilder.newClient(config);

回答by Hemant Daga

It worked for me by adding all required Hymanson Jars. Added these jars

通过添加所有必需的Hyman逊罐子,它对我有用。添加了这些罐子

  • Hymanson-annotations-2.8.7.jar,
  • Hymanson-core-2.8.7.jar
  • Hymanson-databind-2.8.7.jar
  • Hymanson-jaxrs-base-2.8.7.jar
  • Hymanson-jaxrs-json-provider-2.8.3.jar
  • Hymanson-module-jaxb-annotations-2.8.7.jar
  • Hymanson-annotations-2.8.7.jar,
  • Hyman逊核心2.8.7.jar
  • Hyman逊-数据绑定-2.8.7.jar
  • Hymanson-jaxrs-base-2.8.7.jar
  • Hymanson-jaxrs-json-provider-2.8.3.jar
  • Hymanson-module-jaxb-annotations-2.8.7.jar