Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson-XML. How can I ignore an XML attribute?

Tags:

java

xml

jackson

I have the following XML file:

<Channel>
    <name>test</name>
    <number type="example">123</number>
</Channel>

and the following Java class:

public class Channel {
    public String name;
    public Integer number;

    @Override
    public String toString() {
        return "Channel{" + "name='" + name + '\'' + ", number=" + number + '}';
    }
}

I want to use Jackson to read the XML into an object of class Channel. Here's how I tried to do this:

JacksonXmlModule module = new JacksonXmlModule();
XmlMapper xmlMapper = new XmlMapper(module);
InputStream stream = App.class.getResourceAsStream(FILE_NAME);

Channel value = xmlMapper.readValue(stream, Channel.class);
System.out.println(value);

But I get the following error:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int out of START_OBJECT token
at [Source: java.io.BufferedInputStream@158ec7a7; line: 3, column: 5] (through reference chain: org.robinski.Channel["number"])

I expected to get the following output:

Channel{name='test', number=123}

I know that it's the XML attribute 'type="example"' that causes this problem. When I remove the attribute, everything works. But I cannot just manually remove it, because normally I receive the XML from external source.

You can see the whole source code here: http://pastie.org/9870866 .

What can I do to parse the XML file into an object of class Channel using Jackson?

like image 543
JustAC0der Avatar asked Nov 17 '25 19:11

JustAC0der


1 Answers

Not seeing a way, I would feel inclined to take the attribute too.

public class Channel {

    static class Number {
        public String type; // transient too?

        @JacksonXmlText
        public Integer value;

        public String toString() {
            ...
        }
    }

    public String name;
    public Number number;

    @Override
    public String toString() {
        ...
    }
}
like image 60
Joop Eggen Avatar answered Nov 19 '25 08:11

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!