某处的聪明人设计了这样的 xml:
<node>
<subnode value="sv1"/>
<anotherSubNode value="asv" />
</node>
我想将其映射到 POJO 对象,如下所示:
class Node {
String subnode;
String anotherSubNode;
//...
}
而不是
class NodeValue {
@XmlAttribute
String value;
}
class Node {
NodeValue subnode;
NodeValue anotherSubNode;
/...
}
有没有一种方法可以使用标准 java xml 编码(marshal)处理来有效地做到这一点?或者甚至是非标准的?
最佳答案
安XmlAdapter是最简单、最通用的解决方案。字符串字段的适配器如下所示:
public class NodeValueStringAttrMarshaller extends XmlAdapter<NodeValueElement, String> {
@Override
public NodeValueElement marshal(String v) throws Exception {
return new NodeValueElement(v);
}
@Override
public String unmarshal(NodeValueElement v) throws Exception {
if (v==null) return "";
return v.getValue();
}
}
如果您有其他类型的字段,例如 Long 或 Boolean,则必须实现其他(同样简单)的适配器。
还需要一个通用的字段对象来编码:
@XmlAccessorType(XmlAccessType.FIELD)
public class NodeValueElement {
@XmlAttribute(name="value")
String value;
public NodeValueElement() {
}
public NodeValueElement(String value) {
super();
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
要使用适配器,您必须在 POJO 中注释适当的字段:
class Node {
@XmlJavaTypeAdapter(value=NodeValueStringAttrMarshaller.class)
String subnode;
@XmlJavaTypeAdapter(value=NodeValueLongAttrMarshaller.class)
Long anotherSubNode;
//...
}
关于java - 将字段编码为具有字段名称的子节点的值属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720754/