簡體   English   中英

如何使用 Java 和 Spring Boot 使用 XML 數據

[英]How to consume XML data using Java and Spring Boot

我需要使用 XML 數據。 我的 XML 片段:

<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>

這是實體類的代碼:

@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
}

我不知道如何編寫服務和控制器來使用這個 XML。

您可以使用 spring 的 restTemplate 向端點發出(獲取/發布)請求並將響應作為字符串獲取,例如:

final ResponseEntity<String> response = restTemplate.getForEntity(endpointUrl, String.class);

並將其映射到 XML 或 JOSN。 更直接的版本可能是在響應中請求和期望數據模型,例如:

final ResponseEntity<Company> response = restTemplate.getForEntity(endpointUrl, Company.class);

在這種情況下,您必須向模型類添加一些 XML 綁定注釋,例如:

@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

您可以通過向請求添加一個額外的標頭來從服務端點請求 JSON 響應,例如:

Accept: application/json

那么數據模型類就不能省略所有的 XML 綁定注解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM