简体   繁体   中英

XStream: how to marshal/unmarshal lists in a custom converter?

I have the following class (legacy; not annotatable) that is serialized with a custom converter:

class Test {

    // some other variables

    List<SomeType> someTypeList;

}

A properly working converter for SomeType is already available. However I want the list to be serialized as if it was annotated with @XStreamAlias("someTypes").

In the end I expect the following format for someTypeList:

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

How do I have to implement the marshal/unmarshal method to get the desired output? Calling context.convertAnother(someTypeList) didn't yield the expected result as the surrounding <someTypes> tag was missing.

You wise to get the structure:

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

Look at the following code. For your list you need to tag:

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

Now, depending on what you got inside, you might need to create a custom converter. To refer to that you change a bit like this:

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

Then create a converter class ( YourOwnConverter ) that would know how to un/marshal:

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 ;
}

Use this as example: http://x-stream.github.io/converter-tutorial.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM