Vova Yatsyk
Vova Yatsyk

Reputation: 3525

Can't parse empty xml property with attribute

I have the following xml:

<prog>
    <prop1 attr="attr"> </prop1> 
    <prop2>some</prop2> 
</prog>

I have the following class for represent it:

@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "prog")
public class Prog {

    @JacksonXmlProperty(localName = "prop1")
    private String prop1;

    @JacksonXmlProperty(localName = "prop2")
    private String prop2;

    //getters, setters
}

But it fails with the following error: Could not read document: Can not instantiate value of type [simple type, class com.xxx.xxx.entities.ro.Prog] from String value ('some'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@1bbaaffd; line: 18, column: 36]

The following xmls CAN be parsed well (using class above):

without attribute

<prog>
    <prop1> </prop1> 
    <prop2>some</prop2> 
</prog>

empty prop1 (instead of spaces)

<prog>
    <prop1 attr="attr"></prop1> 
    <prop2>some</prop2> 
</prog>

not empty prop1

<prog>
    <prop1 attr="attr"> g</prop1> 
    <prop2>some</prop2> 
</prog>

Does original xml valid? And how can I parse it?
Actually I need to skip attr, but I also tried to represent it as Object:

@JsonIgnoreProperties(ignoreUnknown = true)
public class XmlElement {

    @JacksonXmlText
    private String value;

    //getters, setters
}

UPDATE: I invoke parsing while using SpringMVC controllers, but it also reproduces with:

String xml = "<prog>" +
        "<prop1 attr=\"att1\"> </prop1>" +
        "<prop2>some</prop2>" +
        "</prog>";
ObjectMapper xmlmapper = new XmlMapper();
Prog prog = xmlmapper.readValue(xml, Prog.class);

Upvotes: 1

Views: 622

Answers (1)

Andremoniy
Andremoniy

Reputation: 34900

It works perfectly with com.fasterxml.jackson of version 2.7.4. But it fails with various errors if some of libraries has another version (for example, jackson-dataformat-xml of earlier versions). So you have to check which versions of com.fasterxml.jackson.core, jackson-annotations and jackson-dataformat-xml are used, and make them the same.

Upvotes: 2

Related Questions