我需要使用 xml 绑定解组映射给出错误。
MyMap.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "MyMap")
public class MyMap {
@XmlElement(name = "Config", required = true)
private final List<Config> config = new ArrayList<Config>();
public List<Config> getConfig() {
return this.config;
}
}
MyAdaptor.java : 公共类 MyAdaptor 扩展 XmlAdapter> {
@Override
public MyMap marshal(Map<String,String> v) throws Exception {
MyMap myMap = new MyMap();
List<Config> aList = myMap.getConfig();
for ( Map.Entry<String,String> e : v.entrySet() ) {
aList.add(new Config(e.getKey(), e.getValue()));
}
return myMap;
}
@Override
public Map<String,String> unmarshal(MyMap v) throws Exception {
Map<String,String> map = new HashMap<String,String>();
for (Config e : v.getConfig()) {
map.put(e.getKey(), e.getValue());
}
return map;
}
}
配置.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Config")
public class Config {
@XmlAttribute(name = "key", required = true)
private final String key;
@XmlAttribute(name = "value", required = true)
private final String value;
public Config(String key, String value) {
this.key = key;
this.value = value;
}
public Config() {
this.key = null;
this.value = null;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
客户端代码:
String getConfigurationMethod = baseUrl + "getConfiguration";
byte[] getConfigurationResponse = (byte[]) this
.sendGetMethod(getConfigurationMethod);
unmarshaller = this.getUnmarshaller(MyMap.class);
reader = new StringReader(new String(getConfigurationResponse));
MyMap myMap = (MyMap) unmarshaller.unmarshal(reader);
错误信息:
JAXBException:意外元素(uri:“”,本地:“workConfigRestWrapper”)。预期元素是 <{}Config>、<{}MyMap> javax.xml.bind.UnmarshalException:意外元素(uri:“”,本地:“workConfigRestWrapper”)。预期元素是 com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:662) 上 com.sun.xml.bind.v2 上的 <{}Config>、<{}MyMap>。 runtime.unmarshaller.Loader.reportError(Loader.java:258) 在 com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:253) 在 com.sun.xml.bind.v2。 runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:120) 在 com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1063) 在 com.sun.xml.bind。