简体   繁体   中英

Consume XML in Java with Jersey

I've build a web application that produces XML code of an object. To my suprise, the xml produced is completely correct and in the format I wanted it. However, I'm now making a method that consumes XML in the same format and turn it back in an object. How can I test if it is working?

I've tried using a REST extension in chrome that posts the exact same XML that my other method produces, but I get the error: "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." I've also tried putting breakpoints in my code and debugging it that way, but my breakpoints are never even reached.

@GET
@Produces(MediaType.TEXT_XML)
public week_program getXml() {
   week_program weekProgram = new week_program();            
   return weekProgram;
}

@POST    
@Consumes(MediaType.TEXT_XML)
public Response PostXml(week_program weekProgram) {
    System.out.println(weekProgram);
    return Response.status(Status.OK).entity(weekProgram).build();        
}

How can I fix it, or even test correctly if it does actually work?

I would suggest using json instead of XML and Gson from Google .

Since json output is usually smaller than XML (fat free).

Object to JSON

 DataObject obj = new DataObject();
 Gson gson = new Gson();
 String json_string = gson.toJson(obj);

JSON to Object

DataObject obj = gson.fromJson(json_string, DataObject.class);

Here's a tutorial. http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

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