Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize java object as xml attribute with jackson?

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.annotation.XmlAttribute) to realize this.

e.g.

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!

like image 566
Divine Avatar asked Feb 05 '13 16:02

Divine


People also ask

Does Jackson use Java serialization?

Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.

Can ObjectMapper be used for XML?

We can also read XML, using the various readValue APIs that are part of provided by the ObjectMapper. For example, reading some XML from an InputStream into a Java Bean: MyBean bean = objectMapper.

What is XML serialization in Java?

Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.

Does Jackson use serializable?

Introduction of ObjectMapper Class jackson. databind package and can serialize and deserialize two types of objects: Plain Old Java Objects (POJOs)


1 Answers

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.

like image 113
Divine Avatar answered Sep 28 '22 00:09

Divine