javaxmljackson

XmlMapper readValue return object with null value


I receive an Xml like this one from a soap call (I cannot edit the response, I need to work with this):

<soap:Envelope xmlns:soap="url">
    <soap:Body>
        <myResponse 
        xmlns="url2" 
        Id="responseId"/>
    </soap:Body>
</soap:Envelope>

I got an object in java to map this response

@Data
@JacksonXmlRootElement(localName = "soap:Envelope")
public class MyResponse {
    @JacksonXmlProperty(localName = "soap:Body")
    Body body = new Body();

    @JacksonXmlProperty(localName = "xmlns:soap",
            isAttribute = true)
    String soapEnv = "url";

    @Data
    public static class Body {
        @JacksonXmlProperty(localName = "myResponse")
        MyResponse myResponse = new MyResponse();
        @Data
        public static class MyResponse {
            @JacksonXmlProperty(localName = "xmlns",
                    isAttribute = true)
            protected String xmlns = "url1";
            @JacksonXmlProperty(localName = "Id",
                    isAttribute = true)
            protected String responseId;
        }
    }
}

I'm trying to read it like this

var xmlMapper = new XmlMapper();
xmlMapper.configure(
                            SerializationFeature.FAIL_ON_EMPTY_BEANS,
                            false);
xmlMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
xmlMapper.configure(
                            ToXmlGenerator.Feature.WRITE_XML_DECLARATION,
                            true);
xmlMapper.configure(
                            DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                            false);
try {
    return xmlMapper.readValue(response, MyResponse.class);
} catch (JsonProcessingException e) {
    System.out.println(e.getMessage());
}

But I get a MyResponse with responseId null (and all other properties except for xmlns, I only wrote responseId here to keep it as simple as possible).

I think there is something wrong with my XmlMapper configuration (maybe because I got my values into the attributes instead of tags, but I get them like that) can you help me fix it? Thank you.


Solution

  • I think you use the annotation in wrong way.

    <soap:Envelope xmlns:soap="url">
    

    soap - is short name for namespace which is specified with xmlns:soap under url "url".

    Envelope is name of the element within namespace "url".

    So your POJO should start with annotation :

    @JacksonXmlRootElement(localName = "Envelope", namespace="url")
    

    Namespace are sometimes confusing, but in your code you must work always with URL/URI. You can for example receive XML which is same, but use different short name for particular namespace. For example this is same XML :

    <abcd:Envelope xmlns:abcd="url">
      <abcd:Body>
        <myResponse xmlns="url2" Id="responseId"/>
      </abcd:Body>
    </abcd:Envelope>
    

    Radek