Can not deserialize instance of java.lang.String out of START_OBJECT token when trying to deserialize XML

Viewed 273

I am trying to deserialize a message being recieved in an XML soap format. Previously this had been working but due to a change to the source message I am now getting the following issue

Can not deserialize instance of java.lang.String out of START_OBJECT token

I can see that this because of the following in the message....

<FieldExample xsi:type="xsd:string"></FieldExample>

I believe the issue is that it is trying to assign or "cast" an string datatype onto an empty field and so is throwing an error stating that the field is an object and cannot be recognized as a string.

My question is how can I stop the deserializer from trying to read this particular empty field in the first place. This is how I've declared in my Java code using Jackson

@JacksonXmlProperty(localName = "FieldExample", namespace = Namespace.example)
private String fieldExample;

I have tried the following to no success....

@JsonInclude(JsonInclude.Include.NON_EMPTY) 

on the class definition

and

MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

On the mapper creation

Unfortunately the issue still occurs.

1 Answers

Question does not include a code example, posting a working solution with the snippets found in the question.

Given the java class:

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class Foo {

    private String bar;

    @JacksonXmlProperty(localName = "FieldExample")
    private String fieldExample;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public String getFieldExample() {
        return fieldExample;
    }

    public void setFieldExample(String fieldExample) {
        this.fieldExample = fieldExample;
    }
}

The following test passes without any errors you are mentioning:

import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class FooTest {
    @Test
    public void testDeserialize()throws Exception {
        final String xml = "<root xmlns:xsi=\"http://foo.bar\">" +
                                "<bar>test</bar>" +
                                "<FieldExample xsi:type=\"xsd:string\"></FieldExample>" +
                            "</root>";
        final Foo foo =  new XmlMapper(new JacksonXmlModule())
                         .readValue(xml, Foo.class);
        org.junit.Assert.assertEquals("test",foo.getBar());
        org.junit.Assert.assertEquals("",foo.getFieldExample());
    }
}
Related