I need to consume XML data. My XML Snippet:
<TallyTransferResponse>
<Response>
<TransactionDocumentNo>iut-1</TransactionDocumentNo>
<FromLocation>Bangalore</FromLocation>
<ToLocation>Noida</ToLocation>
</Response>
<Response>
<TransactionDocumentNo>iut-2</TransactionDocumentNo>
<FromLocation>Bangalore</FromLocation>
<ToLocation>Mumbai</ToLocation>
</Response>
</TallyTransferResponse>
Here is code for entity class:
@Entity
public class TallyTransferResponse{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String transaction_document_no;
private String from_location;
private String to_location;
public TallyTransferResponse() {}
/**
* @param transaction_document_no
* @param from_location
* @param to_location
*/
public TallyTransferResponse(String transaction_document_no, String from_location, String to_location) {
this.transaction_document_no = transaction_document_no;
this.from_location = from_location;
this.to_location = to_location;
}
//Getters and Setters
}
I'm stuck as to how to write service and controller to consume this XML.
You can use spring's restTemplate to make a (get/post) request to the endpoint and fetch the response as a string like:
final ResponseEntity<String> response = restTemplate.getForEntity(endpointUrl, String.class);
And the map it to XML or JOSN. More straight forward version of this might be requesting and expecting a data model in the response, like:
final ResponseEntity<Company> response = restTemplate.getForEntity(endpointUrl, Company.class);
In this case you will have to add some XML bind annotation to your model class, like:
@XmlRootElement(name="company", namespace="some.namespace" )
@XmlAccessorType(XmlAccessType.NONE)
public class Company {
@XmlAttribute(name="id")
private Integer id;
@XmlElement(name="company_name")
private String companyName;
.....
//the rest of the class is omitted
You can request a JSON response from the service endpoint with adding one additional header to the request, like:
Accept: application/json
Then the data model class cant omit all the XML binding annotations.
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.