[英]How to serialize java object as xml attribute with jackson?
is there a way to serialize a java var (eg int) via jackson as an xml attribute? 有没有办法通过jackson序列化java var(例如int)作为xml属性? I can not find any spezific jackson or json annotation (@XmlAttribute @javax.xml.bind.annotation.XmlAttribute) to realize this.
我找不到任何特定的jackson或json注释(@XmlAttribute @ javax.xml.bind.annotation.XmlAttribute)来实现这一点。
eg 例如
public class Point {
private int x, y, z;
public Point(final int x, final int y, final int z) {
this.x = x;
this.y = y;
this.z = z;
}
@javax.xml.bind.annotation.XmlAttribute
public int getX() {
return x;
}
...
}
What I want: 我想要的是:
<point x="100" y="100" z="100"/>
but all I got is: 但我得到的只是:
<point>
<x>100</x>
<y>100</y>
<z>100</z>
</point>
Is there a way to get attributes instead of elements? 有没有办法获取属性而不是元素? Thanks for help!
感谢帮助!
Okay I found a solution. 好的,我找到了解决方案。
It wasn't necessary to register an AnnotaionIntrospector if you use jackson-dataformat-xml 如果使用jackson-dataformat-xml,则无需注册AnnotaionIntrospector
File file = new File("PointTest.xml");
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(file, new Point(100, 100, 100));
The missing TAG was 丢失的标签是
@JacksonXmlProperty(isAttribute=true) @JacksonXmlProperty(isAttribute =真)
so just change the getter to: 所以只需将吸气剂更改为:
@JacksonXmlProperty(isAttribute=true)
public int getX() {
return x;
}
and it works fine. 它工作正常。 Just follow this how to:
只需按照以下方式:
https://github.com/FasterXML/jackson-dataformat-xml https://github.com/FasterXML/jackson-dataformat-xml
@JacksonXmlProperty allows specifying XML namespace and local name for a property;
@JacksonXmlProperty允许为属性指定XML名称空间和本地名称; as well as whether property is to be written as an XML element or attribute.
以及是否将属性写为XML元素或属性。
Have you registered JaxbAnnotationIntrospector ? 你注册了JaxbAnnotationIntrospector吗?
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
// make serializer use JAXB annotations (only)
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.