user6454491
user6454491

Reputation: 158

Returning XML/JSON in Jersey

@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:

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?

Upvotes: 0

Views: 1133

Answers (4)

serxio
serxio

Reputation: 359

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

Upvotes: 0

kartheek vanapalli
kartheek vanapalli

Reputation: 66

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/

Upvotes: 0

dhyanandra singh
dhyanandra singh

Reputation: 1141

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);
      });

Upvotes: 1

USer22999299
USer22999299

Reputation: 5674

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

Upvotes: 2

Related Questions