0
@GET @Path("/ids/{printerid}") @Produces({"application/json", "application/xml"}) public Printer getPrinter(@PathParam("printerid") String printerId) { ... } 

is a piece of a code example found here: https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e2089

What I understand is:

  • the method getPrinter is called when the HTTP method GET is called on the path /ids/{printerid}
  • the method Produces either a json or an xml result
  • the method returns an Object of type Printer, identified by the ID provided in the URI

What I don't understand is, how the returned Printer is represented as an xml/json document. We return a Printer in this method, so how do we get an xml/json file from that?

4 Answers 4

2

This is the whole idea of Jersy layer / spring controller, they encapsulate it and convert the class to JSON. You can have the same result with Gson

Gson gson = new Gson(); String json = gson.toJson(printerObject); System.out.println(json); 

Not sure if Jersy is using Gson, but the logic will be probably the same

Sign up to request clarification or add additional context in comments.

3 Comments

Ok. As I understand it, I don't have to do anything for the conversion itself. Now suppose I call a method, which produces XML, how do I display it in the client (browser) in my case. When I call the method, nothing is displayed
Check in the web browser network console, check the response body or use fiddler to see what data you get from the server and make sure you parse it correctly
thanks. It seems that there is an internal server error. At least I vaguely know where I should look now
1

When you request for a service from clien side you always mentioned content type there which indicates the response accepted in xml or json.

$http({ method: "GET", contentType: "application/json", url: baseUrl + '/xyz' + id }).success(function (response) { console.log(response); // you can also use console.log(JSON.stringify(response); }).error(function (response) { console.log(response); }); 

Comments

0

Based on "Content-type" in the request, jersey will decide the representation.

There are many frameworks that provide support for xml/json representation for jersey. Jackson and JAXB are very popular and efficient frameworks for JSON and XML processing in jersey.

Take a look to official Jersey documentation for different frameworks : https://jersey.java.net/documentation/latest/media.html

You can find many articles related to XML and JSON support in jersey here :
http://www.mkyong.com/tutorials/jax-rs-tutorials/

Comments

0

You need to send the header "accept" in the request with the desired value: "application/json" or "application/xml".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.