Why doesn't Jackson XML deserialization respect any annotations?

piepera :

I've been reading tutorials about Jackson XML deserialization (#1, #2). I tried to follow along with examples by writing some java code:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.xml.XmlMapper;

public class JacksonDemo {
    @JsonPropertyOrder({"age", "id", "name"})
    public static class Person {
        @JsonProperty("_id")
        public String id;
        public String name;
        public int age;
        @JsonIgnore
        public String note;
    }

    public static void main(String[] args) throws Exception {
        XmlMapper mapper = new XmlMapper();
        Person value = new Person();
        value.age = 4;
        value.id = "12345";
        value.name = "George";
        value.note = "Invalid";
        String s = mapper.writeValueAsString(value);
        System.out.println(s);
    }
}

According to the tutorials, this should result in the following output:

<Person><age>4</age><_id>12345</_id><name>George</name></Person>

However, it instead results in the following errant output:

<Person><id>12345</id><name>George</name><age>4</age><note>Invalid</note></Person>

The properties are in the incorrect order, the "id" field has the incorrect XML element, and the "note" field is incorrectly included. Supposedly, the various java annotations should change Jackson's behavior but it seems like all annotations are being ignored. Does anybody know why this is?

This is with jackson-xml-databind 0.6.2, jackson-annotations 2.6.0, and jackson 2.6.5.

Michał Ziober :

jackson-xml-databind in version 0.6.2 was released on Nov 11, 2011. In linked articles there is a suggestion to use jackson-dataformat-xml library.

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.0</version>
</dependency>

The newest version is 2.9.8 and I suggest to use it. Below you can find Maven dependencies for which your example should work as expected:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version.core}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version.core}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>${jackson.version.core}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version.core}</version>
</dependency>

where jackson.version.core is 2.9.8.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=106924&siteId=1