How to serialize java object as xml attribute with jackson?

后端 未结 2 1831
说谎
说谎 2021-01-17 23:33

is there a way to serialize a java var (e.g. int) via jackson as an xml attribute? I can not find any spezific jackson or json annotation (@XmlAttribute @javax.xml.bind.anno

相关标签:
2条回答
  • 2021-01-17 23:48

    Okay I found a solution.

    It wasn't necessary to register an AnnotaionIntrospector if you use jackson-dataformat-xml

    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)

    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

    @JacksonXmlProperty allows specifying XML namespace and local name for a property; as well as whether property is to be written as an XML element or attribute.

    0 讨论(0)
  • 2021-01-17 23:48

    Have you registered 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);
    
    0 讨论(0)
提交回复
热议问题