简体   繁体   中英

Restful WebService using Jersey transform xml to json format

Hi I have written the simple "hello" message below in xml format and it works, my question is how can I transform the xml "hello" message below in Json format, what sort of changes should I enter?

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

@Path("/hello")
public class Hello {
    //Called if XML is request
        @GET
        @Produces(MediaType.TEXT_XML)
        public String sayXMLHello() {
            return "<?xml version=\"1.0\"?>" + "<hello> Hello, World!" + "</hello>";
        }
    //Called if JSON is request

Prepare a domain object.

@XmlRootElement
public class Hello {

    @XmlValue
    private String value = "Hello, World!";
}

Now JAX-RS can do what you want.

@Path("/hello")
public class HelloResource {

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Hello read() {
        return new Hello();
    }

    @GET
    @Path("/world.xml")
    @Produces({MediaType.APPLICATION_XML})
    public Hello readXml() {
        return new Hello();
    }

    @GET
    @Path("/world.json")
    @Produces({MediaType.APPLICATION_JSON})
    public Hello readJson() {
        return new Hello();
    }
}

Now any client can choose what format they want to get with following HTTP header.

Accept: application/xml

or

Accept: application/json

Say,

$ curl http://.../hello
$ curl -H "Accept: application/xml" http://.../hello
$ curl -H "Accept: application/json" http://.../hello
$ curl http://.../hello/world.xml
$ curl http://.../hwllo/world.json

References

The media type defines the Kind of output.

Change mediatype from @Produces(MediaType.TEXT_XML)

To @Produces(MediaType.APPLICATION_JSON)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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