xstream不映射字段_如何使用xstream将哈希图映射到XML中的键值属性

I have the following entity:

@XStreamAlias("entity")

public class MapTestEntity {

@XStreamAsAttribute

public Map myMap = new HashMap<>();

@XStreamAsAttribute

public String myText;

}

I use it with xstream like:

MapTestEntity e = new MapTestEntity();

e.myText = "Foo";

e.myMap.put("firstname", "homer");

e.myMap.put("lastname", "simpson");

XStream xstream = new XStream(new PureJavaReflectionProvider());

xstream.processAnnotations(MapTestEntity.class);

System.out.println(xstream.toXML(e));

and get the following xml:

lastname

simpson

firstname

homer

But I need to map the HashMap to attributes in xml like:

How can I do that with XStream? Can I use a custom converter or mapper or something like that? TIA!!

(Of course my code needs to be ensure that are no duplicates in xml attributes.)

解决方案

I wrote an own Converter:

public class MapToAttributesConverter implements Converter {

public MapToAttributesConverter() {

}

@Override

public boolean canConvert(Class type) {

return Map.class.isAssignableFrom(type);

}

@Override

public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

Map map = (Map) source;

for (Map.Entry entry : map.entrySet()) {

writer.addAttribute(entry.getKey(), entry.getValue().toString());

}

}

@Override

public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

Map map = new HashMap();

for (int i = 0; i < reader.getAttributeCount(); i++) {

String key = reader.getAttributeName(i);

String value = reader.getAttribute(key);

map.put(key, value);

}

return map;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值