XStream:如何在自定义转换器中编组/解组列表?

时间:2010-09-27 14:19:57

标签: java converter xstream

我有以下使用自定义转换器序列化的类(遗留;不可注释):

class Test {

    // some other variables

    List<SomeType> someTypeList;

}

SomeType的正常工作转换器已经可用。但是我希望列表被序列化,好像它是用@XStreamAlias(“someTypes”)注释的。

最后,我希望someTypeList的格式如下:

<someTypes class="list-type">
    <someType>
        ....
    </someType>
    ...
</someTypes>

如何实现marshal / unmarshal方法以获得所需的输出?调用context.convertAnother(someTypeList)没有产生预期的结果,因为缺少周围的<someTypes>标记。

2 个答案:

答案 0 :(得分:3)

你明智地得到结构:

<someTypes class="list-type">  
<someType>  
....  
</someType>  
...  
</someTypes>

查看以下代码。对于您的列表,您需要标记:

@XStreamImplicit(itemFieldName="someType")  
List<someType>List;

现在,根据您的内容,您可能需要创建自定义转换器。要指的是你改变了这样的一点:

@XStreamImplicit(itemFieldName="someType")  @XStreamConverter(YourOwnConverter.class)  
List<SomeType> someTypeList;

然后创建一个知道如何取消/编组的转换器类(YourOwnConverter):

public boolean canConvert(Class type) 
{
    return type.equals(SomeType.class);
}

public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) 
{
    SomeType mytype = (SomeType) source;
    writer.addAttribute("position", mytype.getPosition());
    writer.setValue(mytype.getId());
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) 
{
    SomeType mytype = new SomeType();
    String position =  reader.getAttribute("position");
    ......  
        return mytype ;
}

以此为例: http://x-stream.github.io/converter-tutorial.html

答案 1 :(得分:0)

在配置过程中是否在xstream对象上调用了addImplicitCollection导致someTypes标记被跳过?

相关问题