【发布时间】:2021-08-04 03:25:08
【问题描述】:
我正在尝试实现this,其中
<SomeXml>
<SomeData>...</SomeData>
<InputData>
<Param key="key1" value="value1" />
<Param key="key2" value="value2" />
</InputData>
<OutputData>
<Param key="key3" value="value3" />
</OutputData>
</SomeXml>
变成
public class SomeXml {
private SomeData someData;
private Map<String, String> inputData;
private Map<String, String> outputData;
}
inputData map 有 (key1, value1), (key2, value2) 而 outputData map 有 (key3, value3)。
这是我写的;
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class MapElement {
@XmlAttribute(name = "key')
private String key;
@XmlAttribute(name = "value")
private String value;
}
@NoArgsConstructor
public class MapAdapter extends XmlAdapter<MapElement[], Map<String, String>> {
public MapElement[] marshal(Map<String, String> args) throws Exception {
MapElement[] mapElements = new mapElement[args.size()];
int i = 0;
for (Map.Entry<String, String> entry : args.entrySet()) {
mapElements[i++] = new MapElement(entry.getKey(), entry.getValue());
}
return mapElements;
}
public Map<String, String> unmarshal(MapElement[] args) throws Exception {
Map<String, String> m = new TreeMap<>();
for (MapElement elem : args) {
m.put(elem.getKey(), elem.getValue());
}
return m;
}
}
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessorType.FIELD)
@XmlRootElement
public class SomeXml {
@XmlElement
private SomeData someData;
@XmlJavaAdapter(MapAdapter.class)
@XmlElement(name = "InputData")
private Map<String, String> inputData;
@XmlJavaAdapter(MapAdapter.class)
@XmlElement(name = "OutputData")
private Map<String, String> outputData;
}
据我所知,InputData 和 OutputData 映射是非空的,因此正在创建它们,但是在检查 MapAdapter.unmarshal 函数的参数长度时,它为零,这意味着我不是能够正确读取标记的信息。任何帮助将不胜感激。
【问题讨论】: