java - 如何使用 jaxb 将包含相同元素的不同类型的元素映射到单个 java 类 objetc
问题描述
我的问题是客户端 sendind xml 请求包含具有相同名称的不同类型的元素,我需要转换为 java 对象。我在下面添加请求。第一个请求是:-
<root>
<params>
<game>1</game>
</params>
</root>
第二个是:-
<root>
<params>
<game>
<id>1</id>
<name>Lucky 7</name>
<translation>Lucky 7</translation>
</game>
</params>
</root>
我已经查看了stakeoverflow,但我没有得到解决方案。希望有人可以帮助添加到单个java类中,而不是使用多个java类。
解决方案
父元素同时具有子元素和文本值,使用@XmlMixed
注解通过 JAXB 解组提取父元素的文本值
尝试以下示例,
游戏.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<game>1</game> <!-- text value -->
<game>
<id>1</id> <!-- child element -->
<name>Lucky 7</name>
<translation>Lucky 7</translation>
</game>
</root>
根.java
@XmlRootElement
public class Root {
private List<Game> listGame;
@XmlElement(name="game")
public List<Game> getListGame() {
return listGame;
}
public void setListGame(List<Game> listGame) {
this.listGame = listGame;
}
}
游戏.java
@XmlRootElement
public class Game {
private List<String> textValue;
private String id;
private String name;
private String translation;
@XmlMixed
public List<String> getTextValue() {
return textValue;
}
public void setTextValue(List<String> textValue) {
this.textValue = textValue;
}
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getTranslation() {
return translation;
}
public void setTranslation(String translation) {
this.translation = translation;
}
}
使用 JAXB 解组,
File file = new File("game.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root) jaxbUnmarshaller.unmarshal(file);
for (int i = 0; i < root.getListGame().size(); i++) {
System.out.println("Game Object "+(i+1));
if(root.getListGame().get(i).getTextValue().size()>1){
System.out.println("ID :"+root.getListGame().get(i).getId());
System.out.println("Name :"+root.getListGame().get(i).getName());
System.out.println("Translation :"+root.getListGame().get(i).getTranslation());
}else{
System.out.println("Value :"+root.getListGame().get(i).getTextValue().get(0));
}
System.out.println("------------------------------------");
}
输出,
Game Object 1
Text Value :1
------------------------------------
Game Object 2
ID :1
Name :Lucky 7
Translation :Lucky 7
------------------------------------
欲了解更多信息,https://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlMixed.html
谢谢,
推荐阅读
- docker - docker-compose 和覆盖变量
- ios - 通过端口号识别调试
- database - 如何删除符合特定条件的 MongoDB 数据库?
- javascript - 如何使用 (CSS/HTML/Javascript) 在 Hover 上添加带有动画的字母
- html - 如何确保跨度的内容在 CSS 中向右而不是向左增长
- c# - 无法将证书粘贴到受信任的根证书颁发机构存储中。访问被拒绝
- java - 为什么不能通过两个参数交换数组的两个元素?
- netcdf - NetCDF 重新排序维度
- reactjs - 从 React 中的表单发布方法获取响应
- php - 选择数据时子查询返回多于 1 行