反序列化为XML属性(Java)提供的映射键值对

时间:2015-12-07 15:26:40

标签: java xml xstream xml-deserialization

我想要这个XML

Map<String, String>

要反序列化为<firstTag/>,以便仅考虑通过{foo=One, bar=Two}内的属性提供的键和值。 这是所需的输出映射:

export class DefectResource { setFormattedDateForDefect = (defect) => { defect.startFormatted = this.dateConverter.convertFromUnixDate(defect.start); defect.finishFormatted = this.dateConverter.convertFromUnixDate(defect.finish); return defect; }; setFormattedDateForDefects = (defects) => { return _.map(angular.fromJson(defects), this.setFormattedDateForDefect); }; }

使用XStream,jackson-dataformat-xml或任何流行的解组库。

1 个答案:

答案 0 :(得分:0)

我需要为此实现Converter

public class MyConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }

    @Override
    public void marshal(Object arg0, HierarchicalStreamWriter writer, MarshallingContext context) {}

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

        Map<String, String> map = new HashMap<String, String>();
        reader.moveDown();  // Get down to the firstTag and secondTag level.

        while(reader.hasMoreChildren()) {
            if(reader.getNodeName().equals("firstTag")) {
                while(reader.hasMoreChildren()) {
                    reader.moveDown();
                    String key = reader.getAttribute("key");
                    String value = reader.getAttribute("value");
                    map.put(key, value);
                    reader.moveUp();
                }
            }
        }
        return map;
    }
}

然后使用它:

XStream xstream = new XStream();
xstream.alias("root", java.util.Map.class);
xstream.registerConverter(new MyConverter());

String xml = ...
Map<String, String> map = (Map<String, String>) xstream.fromXML(xml);