user6454491 user6454491 - 5 months ago 29
Java Question

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?

Answer

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

Comments