Creating a POJO for a RESTful Web Service

We generate POJOs from WSDL / XSD in SOAP services. How do we generate POJOs when consuming a RESTful web service?

+4
source share
1 answer

Since you do not have WSDL or WADL for the service (a relatively common situation), you will have to do it in a difficult way.

One possible way that a service accepts XML is to write XSD, which describes the documents that it receives and returns. It’s not so difficult if you have ever written XSD before and you use an editor designed to help with this kind of work (I use the one that is in Eclipse, but there are many others). Otherwise, just write POJO yourself. I advise storing such POJOs very simple, possibly without any methods, as well as just public fields and annotations. Key notes to know:

  • @XmlRootElement- these are the names of the elements that will form the outer part of the message going in any direction. Go to class.
  • @XmlElement - puts a field to display as a sub-element of the message.
  • @XmlAttribute - indicates a field to display as an attribute.
  • @XmlType - , .

, POJO :

@XmlRootElement
public class Example {
    @XmlAttribute
    public String pqr;
    @XmlElement
    public String abc;
    @XmlElement
    public List<String> def = new ArrayList<String>();
}
Example example = new Example();
example.abc = "oscar";
example.def.add("bert");
example.def.add("ernie");
// Omitting the attribute; null maps to absence/optionality

JAXBContext c = JAXBContext.newInstance(Example.class);
Marshaller m = c.createMarshaller();
m.marshal(example, System.out);

unmarshalling ( JAXB Unmarshaller, ) .

JSON XML, Jettison . ( , / DOM JSON JAXB.)

0

All Articles