Reputation: 3169
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?
Upvotes: 3
Views: 8607
Reputation: 109613
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() {
...
}
}
Upvotes: 4