我正在尝试解组以下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 & MMS</setting>
<setting>MMS</setting>
<setting>WAP</setting>
</settings>
</InfoResult>
带标题的
Content-Type →application/vnd.mobilethink.setting-v1+xml
问题,如果首先restTemplate解释为json所以我试图使用此处找到的代码强制内容处理程序: Ignoring DTDs when unmarshalling with EclipseLink MOXy
但我得到了编组错误。所以我深入研究并手动完成:
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();
}
但我仍然有一个编组的例子:
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)
请在此处帮助指出错误的代码。
答案 0 :(得分:1)
我最近遇到了类似的问题。
从发布的代码看起来Jaxb2Marshaller
未正确初始化。有必要设置documentation中提到的contextPath
或classesToBeBound
属性。
初始化的正确代码示例:
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(RootEntity.class);
marshaller.afterPropertiesSet();