XStream 不同字段的相同类(Map.class)的不同别名 [英] XStream different alias for same class (Map.class) for different fields
问题描述
我正在使用 XStream 来转换具有 java.util.Map 类型字段的 Java 类.我有一个 java.util.Map 转换器,它将 Map 的键显示为 xml 元素,将 map 的值显示为 xml 元素的值.我已经使用 registerConverter 方法注册了转换器.当我执行编组时,我得到以下输出.
I am using XStream to convert a Java class which has fields of the type java.util.Map. I have a converter for java.util.Map which displays the key of the Map as an xml element and the value of the map as the value for the xml element. I have registered the converter using registerConverter method. When I perform the marshalling, I get the following output.
<cart account_id="123" shift_id="456" account_postings_id="641">
<supervisor_id>555</supervisor_id>
<payments>
<map sequence="1">
<amount>123.45</amount>
<billing_method>12345</billing_method>
<form>card</form>
<delivery_mode>Q</delivery_mode>
</map>
<map sequence="2">
<amount>123.45</amount>
<person_id>2333</person_id>
<form>cash</form>
<delivery_mode>Q</delivery_mode>
</map>
</payments>
<items>
<map sequence="3">
<amount>1.00</amount>
<type>pay_toll</type>
<toll_id>1234</toll_id>
</map>
</items>
</cart>
我想根据类中的字段名称使用不同的标签,而不是出现地图标签.例如,Payments 列表将具有标签名称支付,而 Items 列表将具有每个 Map 元素的标签名称项目.
Instead of the map tags appearing, I would want to use different tags based on the field name in the class. For example, the Payments list will have tag name payment and the Items list will have a tag name item for each Map element.
如何根据同一个类中的字段动态设置别名?
How do we dynamically set alias based on field in the same class?
-阿南德
推荐答案
我使用 XStream
来创建原子提要报告.内容中的条目可以是不同的对象类,我想动态地使用类名.这是我的解决方案.我创建了一个 ObjectContentConverter
并传递了 XStream
,然后使用 xstream.aliasField() 和 getClass().getSimpleName()
.>
I used XStream
to create atom feed reports. Entries in the contents can be of different object classes and I wanted to use the class name dynamically. Here is my solution. I created a ObjectContentConverter
and passed the XStream
on, and then use xstream.aliasField() with getClass().getSimpleName()
.
private class ObjectContentConverter implements Converter {
XStream xStream;
private ObjectContentConverter(XStream xStream) {
this.xStream = xStream;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
String className = WordUtils.uncapitalize(source.getClass().getSimpleName());
xStream.aliasField(className, Content.class, "objectContent");
xStream.marshal(source, writer);
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean canConvert(Class type) {
return true; //To change body of implemented methods use File | Settings | File Templates.
}
}
xStream.registerLocalConverter(Content.class, "objectContent", new ObjectContentConverter(xStream));
这篇关于XStream 不同字段的相同类(Map.class)的不同别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!