gpt4 book ai didi

java - 如何在 JAXB Adapter 中使用属性作为键、使用整个元素作为值将复杂元素解析为 Map

转载 作者:行者123 更新时间:2023-12-02 00:44:21 25 4
gpt4 key购买 nike

我想将复杂的 XML 元素列表解析为 Map,其中键是一个属性,值是整个对象/元素。

这是我的 XML 示例:

<product>
<documents>
<document code="100" clazz="DocumentA">
<properties>
<property name="PropA" value="123" />
<property name="PropB" value="qwerty" />
<property name="PropC" value="ABC" />
</properties>
</document>
</documents>
</product>

我的类(class)文档示例:

public class Document {
private Integer code;
private String clazz;
private List<Propertiy> properties;

//getters and setters...
}

我不知道是否可行,但我想将文档元素解析为Map,其中关键是属性代码。

有人可以帮助我吗?

最佳答案

您可以尝试使用适配器。让我们开始根据您的 xml 构建 POJO。首先你有产品:

@XmlRootElement
public class Product {

@XmlElementWrapper(name = "documents")
@XmlElement(name = "document")
private List<Document> documents;
}

然后该产品中的文档:

@XmlRootElement
public class Document {

@XmlAttribute
private Integer code;
@XmlAttribute
private String clazz;
@XmlElement(name = "properties")
private Properties properties;

}

在属性内,我们使用适配器来获取所需的 map :

@XmlAccessorType(XmlAccessType.FIELD)
public class Properties {

@XmlElement(name = "property")
@XmlJavaTypeAdapter(MyMapAdapter.class)
private Map<String, String> properties;
}

我们的适配器将以一种能够理解传入的 xml 的方式获取它,并将其适应其他内容(即 map )。因此,让我们首先为该属性创建一个 POJO,如 xml 中所示:

@XmlAccessorType(XmlAccessType.FIELD)
public class Property {

@XmlAttribute
private String name;
@XmlAttribute
private String value;

public String getName() {
return name;
}

public String getValue() {
return value;
}
}

然后我们在适配器中使用它:

public class MyMapAdapter extends XmlAdapter<Property, Map<String, String>> {

private HashMap<String, String> hashMap = new HashMap<String, String>();

@Override
public Map<String, String> unmarshal(Property v) throws Exception {
hashMap.put(v.getName(), v.getValue());
return hashMap;
}

@Override
public Property marshal(Map<String, String> v) throws Exception {
// do here actions for marshalling if u also marshal
return null;
}
}

运行此命令将解码有效负载,并且它将根据需要在映射中包含值。希望对您有帮助

关于java - 如何在 JAXB Adapter 中使用属性作为键、使用整个元素作为值将复杂元素解析为 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com