Stranger
Stranger

Reputation: 73

Jackson XML Deserialize single XML tag to Object

I want to deserialize this xml tag:

<source>Test</source>

Into an Object (some java class).

I have the next class:

public class SomeXml{
  private String source;
}

And i'm doing the deserialization this way with Jackson XML:

XmlMapper mapper = new XmlMapper();
SomeXml data = mapper.readValue("<source>Test</source>", SomeXml.class);
System.out.println(data);

But it gives me the next error:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class com.test.SomeXml), not marked as ignorable (one known property: "source"]) at [Source: (StringReader); line: 1, column: 31] (through reference chain: com.test.SomeXml[""])

¿So how can i deserialize that single xml tag into an object/pojo?

Any help is appreciated!!

Upvotes: 0

Views: 1140

Answers (1)

Alberto
Alberto

Reputation: 12899

that XML it's a String, not an object (for Jackson).. instead you should surround it with another tag (that would be your object) containing that string (that would be the attribute)

XmlMapper mapper = new XmlMapper();
SomeXml data = mapper.readValue("<myObj><source>Test</source></myObj>", SomeXml.class);
System.out.println(data);

to check what I've previously said, you can check that this code works fine:

XmlMapper mapper = new XmlMapper();
String data = mapper.readValue("<source>Test</source>", String.class);
System.out.println(data);

Upvotes: 0

Related Questions