因为@Convert标记也可以放在字段上,所以我发现比“ollo”的精彩答案更简洁的代码:
@Root(name = "telegram")
public class Telegram {
@Element
@Convert(Telegram.ConfigConverter.class)
private Map<String, String> config;
public String get(String name) {
return config.get(name);
}
public Map<String, String> getConfig() {
return config;
}
@Override
public String toString() {
return "Telegram{" + "config=" + config + '}';
}
static class ConfigConverter implements Converter<Map<String, String>> {
@Override
public Map<String, String> read(final InputNode configNode) throws Exception {
Map<String, String> map = new HashMap<>();
InputNode cfg = configNode.getNext();
while (cfg != null) {
map.put(cfg.getName(), cfg.getValue());
cfg = configNode.getNext();
}
return map;
}
@Override
public void write(OutputNode node, Map<String, String> value) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
还有测试:
final String xml = "<telegram>\n"
+ " <config>\n"
+ " <foo>yes</foo>\n"
+ " <bar>no</bar>\n"
+ " <baz>maybe</baz>\n"
+ " </config>\n"
+ "</telegram>";
Serializer ser = new Persister(new AnnotationStrategy());
Telegram t = ser.read(Telegram.class, xml);
assertEquals("yes",t.getConfig().get("foo"));
assertEquals("no",t.getConfig().get("bar"));
assertEquals("maybe",t.getConfig().get("baz"));
assertEquals(3, t.getConfig().size());