4

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

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>缺少周围的标签。

4

2 回答 2

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

于 2011-01-18T03:57:54.590 回答
0

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

于 2010-10-06T13:33:32.653 回答