Comfort Chauke
Comfort Chauke

Reputation: 126

org.springframework.oxm.UnmarshallingFailureException: NPE while unmarshalling. Using spring resttemplate and jaxb

I am trying to unmarshall the following xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<InfoResult>
    <resultCode>OK</resultCode>
    <msisdn>263771222608</msisdn>
    <make>Samsung</make>
    <model>Galaxy Grand Neo Plus I9060I</model>
    <settings>
        <setting>Internet</setting>
        <setting>Internet &amp; MMS</setting>
        <setting>MMS</setting>
        <setting>WAP</setting>
    </settings>
</InfoResult>

with header

Content-Type →application/vnd.mobilethink.setting-v1+xml

Problem if first of all restTemplate interprets as json so i tried to force content handler using code found here: Ignoring DTDs when unmarshalling with EclipseLink MOXy

but i am getting mashalling error. So i drilled down to mashalling and done it manually:

private Jaxb2Marshaller marshaller=new Jaxb2Marshaller();

public Object unmarshal(String xmlString) {
    return marshaller.unmarshal(new StreamSource(new StringReader(xmlString)));
}

public InfoResult getSettingsInfo(String msisdn) {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", "application/vnd.mobilethink.setting-v1+xml");
    HttpEntity<String> entity = new HttpEntity<>(headers);
    ResponseEntity<String> infoResultResponseEntity = restTemplate.exchange(INFO_REQUEST_URL, HttpMethod.GET, entity, String.class, msisdn);
    String data = infoResultResponseEntity.getBody();
    Object o = unmarshal(data);
    return new InfoResult();
}

but i am still getting a mashalling exeption:

org.springframework.oxm.UnmarshallingFailureException: NPE while unmarshalling. This can happen on JDK 1.6 due to the presence of DTD declarations, which are disabled.; nested exception is java.lang.NullPointerException
        at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:777)
        at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:753)

Please help point out the bad code here.

Upvotes: 1

Views: 2707

Answers (1)

Tadeusz Kleszcz
Tadeusz Kleszcz

Reputation: 426

I've got similar problem recently.

From the posted code it looks like Jaxb2Marshaller wasn't initialized correctly. It is necessary to set the contextPath or the classesToBeBound property which is mentioned in documentation.

Example correct code to initialize:

Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(RootEntity.class);
marshaller.afterPropertiesSet();

Upvotes: 1

Related Questions