java-使用Moxy处理动态元素名称
作者:互联网
我需要对我的对象FileDocument进行绑定,其中包含对另一个对象元数据的引用.我希望元数据可以具有动态名称,具体取决于其属性值.
我听说过并使用XmlAdapter(也用于Metadata类),但仅用于Map情况.我真的不明白如何使这种情况下工作.
FileDocument的代码段:
@XmlAccessorType(XmlAccessType.FIELD)
public class FileDocument{
//...
protected List<Metadata> metadata;
//...
}
元数据摘要:
@XmlType(name = "metadata")
//@XmlRootElement(name = "metaCollection")
public class Metadata {
//...
@XmlPath(".")
@XmlJavaTypeAdapter(MetaAdapter.class)
Map<String, String> map;
//I'd like to have each element of metadata depend on this attribute.
String source;
}
我想要的输出是这样的
{
"someKeyInFileDocument" : "someValueInFileDocument",
"metadata.source1" : {
"some key inside this metadata" : "some value inside this metadata",
"more!": "more!"
},
"metadata.source2" : {
"yes, the above key" : "looks similar but also different as the above",
"this is another key!" : "inside this source2 thing"
}
}
解决方法:
您可以在此用例中使用EclipseLink JAXB (MOXy)的@XmlVariableNode扩展名:
Java模型
文件文件
我们将在元数据字段上使用@XmlVariableNode批注.这告诉MOXy,应该使用引用对象上指定字段/属性的名称代替元素/键的固定名称.
import java.util.List;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlVariableNode;
@XmlAccessorType(XmlAccessType.FIELD)
public class FileDocument {
@XmlVariableNode("source")
protected List<Metadata> metadata;
}
元数据
我们将在源字段上使用@XmlTransient批注,以防止将其编组(请参阅:http://blog.bdoughan.com/2012/04/jaxb-and-unmapped-properties.html).
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Metadata {
@XmlTransient
String source;
}
示范代码
您可以运行下面的演示代码以查看一切正常.
演示版
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {FileDocument.class}, properties);
Metadata m1 = new Metadata();
m1.source = "metadata.source1";
Metadata m2 = new Metadata();
m2.source = "metadata.source2";
List<Metadata> metadata = new ArrayList<Metadata>();
metadata.add(m1);
metadata.add(m2);
FileDocument fd = new FileDocument();
fd.metadata = metadata;
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(fd, System.out);
}
}
输出量
{
"metadata.source1" : {
},
"metadata.source2" : {
}
}
欲获得更多信息
您可以在我的博客上阅读有关@XmlVariableNode扩展的更多信息:
> http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-json-schema.html
标签:jaxb,moxy,json,java 来源: https://codeday.me/bug/20191121/2053268.html