简体   繁体   中英

Jersey - populate java beans from XML string

I have a Jersey client that is successfully calling a REST service and populating the associated Java Beans CustomerType based on this code:

WebResource service = client.resource(SECURE_BASE_URL);.
CustomerType cust = service.path("customer").path("23210")
    .accept(MediaType.TEXT_XML).get(CustomerType.class);

What I would like is to call the service with

 service.path("customer").path("23210").accept(MediaType.TEXT_XML).get(String.class);

to get the XML string and then convert the XML to the CustomerType bean. I would like to do it this way for logging and to help with designing the system. Is there a ways to convert the XML to the bean?

There are many ways to do that. If your CustomerType class is JAXB-annotated ( @XmlRootElement or whatever), you can simply use an Unmarshaller constructed via a JAXBContext (that you have previously initialized with your packages) like this:

CustomerType customerType = (CustomerType) jaxbContext.createUnmarshaller()
        .unmarshal( new StringReader(yourString) );

Jersey provides a logging filter. This post answers your question.

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