I want to use @Produces({Mediatype.Application_XML , Mediatype.Application_JSON}) in a program that I am writing. I want to use this on only one method, but I am confused that when will it return a JSON object and when will it return an XML page. Here is the code I am writing and in both the cases it returns me an XML feed. I want it to return an JSON object if it does not meet the if-else criterion.
@Path("/{search}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public String getCountryData(@PathParam("search") String search, @QueryParam("ccode") String ccode , @QueryParam("scode") String scode) {
if(ccode.equals("XML")){
return "<note> <to>Tove</to> <from>Jani</from><heading>Reminder</heading> <body>Don't forget me this weekend!</body></note>";
}
return EndecaConn.ConnectDB("Search", search,"mode matchallpartial" );
}
The media type will be part of the request, you shouldn't include it as a query parameter. Below is some sample Java code that would request the data as application/xml
.
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
In your example you could have different methods corresponding to the same path for the different media types.
@Path("/{search}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getCountryDataJSON(@PathParam("search") String search, @QueryParam("scode") String scode) {
return JSON;
}
@Path("/{search}")
@GET
@Produces(MediaType.APPLICATION_XML)
public String getCountryDataXML(@PathParam("search") String search, @QueryParam("scode") String scode) {
return XML;
}
You have to return a Response object with the entity set to your domain entity. The serialization of the xml/json is done automatically.
See: https://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/core/Response.html
yYou can return an entity like this:
Foo myReturn = new Foo(blah,blah,blah)
return Response.ok(myReturn).build()
If you need fine grained serialization you can use annotations on your domain class.
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.