简体   繁体   中英

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:

  • 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?

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

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

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/

您需要在请求中发送带有所需值的标头“accept”:“application/json”或“application/xml”。

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