Java Jersey 演示应用程序中的 MediaType.APPLICATION_XML 和 MediaType.APPLICATION_JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26697102/
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-11 03:04:53  来源:igfitidea点击:

MediaType.APPLICATION_XML and MediaType.APPLICATION_JSON in a Jersey demo application

javajsonrestjerseyjax-rs

提问by user2737950

Once I got this Question Latest Jersey example does not work answered, I run into another curious problem:

一旦我得到这个问题,最新的泽西岛示例不起作用,我遇到了另一个奇怪的问题:

The server, GET methods work fine. I tested and added some test code for helloworld-pure-jax-rsexample, and esp. added a POST request for JSON:

服务器,GET 方法工作正常。我为helloworld-pure-jax-rs示例测试并添加了一些测试代码,尤其是。添加了 JSON 的 POST 请求:

package org.glassfish.jersey.examples.helloworld.jaxrs;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;


@Path("helloworld")
public class HelloWorldResource
{
    public static final String  CLICHED_MESSAGE = "Hello World!";

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getHello()
    {
        return CLICHED_MESSAGE;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getHelloJson()
    {
        return "{ \"message\":" + CLICHED_MESSAGE + "}";
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getHelloHtml()
    {
        return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + CLICHED_MESSAGE
                + "</body></h1>" + "</html> ";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/v2")
    public String getHello2()
    {
        return CLICHED_MESSAGE + " v2";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/{id}")
    public String getHelloId(@PathParam("id") String id)
    {
        return CLICHED_MESSAGE + " Parameter: " + id;
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/id/{id : [a-zA-Z][a-zA-Z_0-9]}")
    public String getHelloIdId(@PathParam("id") String id)
    {
        return CLICHED_MESSAGE + " Parameter: " + id;
    }

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public Response test(String test)
    {
        if (test.equals("test"))
            return Response.status(400).entity("Error: " + test).build();
        return Response.status(200).entity(test).build();
    }

    @POST
    @Path("/test")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response testJSON(Test test)
    {
        String result = "Test JSON created : " + test.getName() + "" + test.getAge();
        // return result;
        return Response.status(200).entity(result).build();
    }

    @POST
    @Path("/test")
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    public Response testXML(Test test)
    {
        String result = "Test XML created : " + test.getName() + "" + test.getAge();
        // return result;
        return Response.status(200).entity(result).build();
    }

}

Here ist the rest of the classes:

这是其余的课程:

package org.glassfish.jersey.examples.helloworld.jaxrs;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;

import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.RuntimeDelegate;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * Hello world application using only the standard JAX-RS API and lightweight
 * HTTP server bundled in JDK.
 *
 * @author Martin Matula (martin.matula at oracle.com)
 */
@SuppressWarnings("restriction")
public class App
{

    /**
     * Starts the lightweight HTTP server serving the JAX-RS application.
     *
     * @return new instance of the lightweight HTTP server
     * @throws IOException
     */
    static HttpServer startServer() throws IOException
    {
        // create a new server listening at port 8080
        HttpServer server = HttpServer.create(new InetSocketAddress(getBaseURI().getPort()), 0);

        // create a handler wrapping the JAX-RS application
        HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new JaxRsApplication(),
                HttpHandler.class);

        // map JAX-RS handler to the server root
        server.createContext(getBaseURI().getPath(), handler);

        // start the server
        server.start();

        return server;
    }

    public static void main(String[] args) throws IOException
    {
        System.out.println("\"Hello World\" Jersey Example Application");

        HttpServer server = startServer();

        System.out.println("Application started.\n" + "Try accessing " + getBaseURI()
                + "helloworld in the browser.\n" + "Hit enter to stop the application...");
        System.in.read();
        server.stop(0);
    }

    private static int getPort(int defaultPort)
    {
        final String port = System.getProperty("jersey.config.test.container.port");
        if (null != port)
        {
            try
            {
                return Integer.parseInt(port);
            }
            catch (NumberFormatException e)
            {
                System.out.println("Value of jersey.config.test.container.port property"
                        + " is not a valid positive integer [" + port + "]."
                        + " Reverting to default [" + defaultPort + "].");
            }
        }
        return defaultPort;
    }

    /**
     * Gets base {@link URI}.
     *
     * @return base {@link URI}.
     */
    public static URI getBaseURI()
    {
        return UriBuilder.fromUri("http://localhost/").port(getPort(8080)).build();
    }
}


public class Test
{
    public int      age     = 0;
    public String   name    = "";

    /**
     * 
     */
    public Test()
    {
        super();
    }

    /**
     * @param age
     */
    public Test(int age)
    {
        super();
        this.age = age;
    }

    /**
     * @param name
     */
    public Test(String name)
    {
        super();
        this.name = name;
    }

    /**
     * @param name
     * @param age
     */
    public Test(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }

    public int getAge()
    {
        return age;
    }

    public String getName()
    {
        return name;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

package org.glassfish.jersey.examples.helloworld.jaxrs;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class JaxRsApplication extends Application
{
    private final Set<Class<?>> classes;

    public JaxRsApplication()
    {
        HashSet<Class<?>> c = new HashSet<Class<?>>();
        c.add(HelloWorldResource.class);
        classes = Collections.unmodifiableSet(c);
    }

    @Override
    public Set<Class<?>> getClasses()
    {
        return classes;
    }
}

This works fine for the plain text post message, but fpr the json (MediaType.APPLICATION_JSON )and xml part (MediaType.APPLICATION_XML) it fails stating not a supported media type. Any idea what could be wrong?

这适用于纯文本帖子消息,但 fpr json (MediaType.APPLICATION_JSON) 和 xml 部分 (MediaType.APPLICATION_XML) 它未能说明不支持的媒体类型。知道有什么问题吗?

采纳答案by Paul Samsotha

JAX-RS has a bunch of built-in handlers that can marshal to and from a few different specific Java types.

JAX-RS 有一堆内置处理程序,可以在几个不同的特定 Java 类型之间进行编组。

Once we start dealing with custom data-binding (marshalling/unmarshalling to Java objects), we are in a different ball game. We now require some other MessageBodyWritersand MesageBodyReaders.

一旦我们开始处理自定义数据绑定(对 Java 对象进行编组/解组),我们就处于不同的球赛中。我们现在需要一些其他的MessageBodyWritersMesageBodyReaders

Fortunately, there are already readers and writers available for XML and JSON data-binding. JAX-RS comes with a standard XML marshalling/unmarshalling, with one caveat.. we must use JAXBannotations. So for your Testclass, assuming it's like this

幸运的是,已经有可用于 XML 和 JSON 数据绑定的读取器和写入器。JAX-RS 带有标准的 XML 编组/解组,有一个警告......我们必须使用JAXB注释。所以对于你的Test班级,假设它是这样的

public class Test {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name;}
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }  
}

to make allow the JAXB providerto unmarshall/marshall, we should provide, at minimum, an @XmlRootElement

为了允许 JAXB提供者解组/编组,我们应该至少提供一个@XmlRootElement

@XmlRootElement
public class Test {
   ....
}

Doing this should allow the XML to work.

这样做应该允许 XML 工作。

As far as the JSON, JSON binding is not a standard par of the specification, but we can simply add a dependency to the project, that will automatically register the needed provider to handle JSON binding. You can look at the pom.xml for the json-moxyexample. You will see this needed dependency

就 JSON 而言,JSON 绑定不是规范的标准部分,但我们可以简单地向项目添加一个依赖项,它将自动注册所需的提供程序来处理 JSON 绑定。您可以查看json-moxy示例的 pom.xml 。你会看到这个需要的依赖

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

What the dependency allows application to do, is marshal/unmarshal jSON to/from our Java objects, using the JAXB annotations. So just by adding this dependency to the pom.xml. The application should work. Just tested.

依赖项允许应用程序执行的操作是使用 JAXB 注释对 Java 对象进行编组/解组 JSON。因此,只需将此依赖项添加到pom.xml. 该应用程序应该可以工作。刚刚测试。