Reputation: 11
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
Upvotes: 0
Views: 2353
Reputation: 2690
The media type defines the Kind of output.
Change mediatype from @Produces(MediaType.TEXT_XML)
To @Produces(MediaType.APPLICATION_JSON)
Upvotes: 0
Reputation: 21978
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
Upvotes: 4