繁体   English   中英

如何编写通过转换为中间对象进行读写的XStream转换器?

[英]How to write XStream converter which write and read via converting to intermediate object?

我有一堂课MyClass 如果我在不实现自定义转换器的情况下对其进行序列化,则该文件将不可读。

我实现了MyClassDTO以及MyClassMyClassDTO之间的转换。

使用XStream标准序列化时, MyClassDTO是人类可读的。

我想编写XStream Converter序列化和反序列化MyClass
Converter.marshal实现应如下:将MyClass对象转换为MyClassDTO然后为MyClassDTO调用默认序列化。

对于Converter.unmarshal :调用MyClassDTO对象的默认反序列化并将其转换为MyClass

如何以简单的方式实现这种行为?

我浏览了XStream Converter教程 ,但没有找到我需要的东西。

我需要填写以下存根:

class MatrixConverter<T> : Converter
    where T : new()
{
    public bool CanConvert(Type type)
    {
        return type == typeof(Matrix<T>);
    }

    public void ToXml(object value, Type expectedType, XStreamWriter writer, MarshallingContext context)
    {
        Matrix<T> matrix = value as Matrix<T>;
        if (matrix == null)
        {
            throw new ArgumentException();
        }
        // the code which I am asked about should follow here
    }

    public object FromXml(Type expectedType, XStreamReader reader, UnmarshallingContext context)
    {
        Matrix<T> matrix = null;

        // the code which I am asked about should follow here

    }
}

假设

MatrixDTO m = new MatrixDTO( matrix );

从内部矩阵类型转换为DTO。

public void ToXml(object value, Type expectedType, 
    XStreamWriter writer, MarshallingContext context)
{
    context.convertAnother(new MatrixDTO( matrix ));
}

public Object FromXml(Type expectedType, 
    XStreamReader reader, UnmarshallingContext context)
{
    return context.convertAnother(context.currentObject(), MatrixDTO.class);
}

在解组情况下,可能必须将其手动插入context.currentObject()中。 自己还没有尝试过。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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