java - 如何使用 Java 和 Spring Boot 使用 XML 数据
问题描述
我需要使用 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 向端点发出(get/post)请求,并将响应作为字符串获取,例如:
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 绑定注解。
推荐阅读
- angular - 错误 NG6001:类 'EaZimmerkatDialogComponent' 列在 NgModule 'AppModule' 的声明中,但不是指令,组件
- react-admin - 在 react-admin 中动态加载资源后如何刷新侧边栏菜单
- rust - 如何解决错误“不能一次多次借用`*self`作为可变变量”
- c# - 如何声明和等待异步委托?
- gitlab-ci - gitlab-ci 扩展作业的结果
- python - 提示用户在 google colab 中加载 csv
- android - 无法以新加坡 asia-southeast1 作为位置写入 firebase 实时数据库
- swift - Twilio 视频轨道附件未在 swift 5 中显示远程参与者的视频
- macos - 找不到 gslcblas 库,无法安装 R 包
- sql - IIS 8.5 ASP.Net 错误删除网站