简体   繁体   English

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

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

I have a class MyClass . 我有一堂课MyClass If I serialize it without implementing custom converter it is not human readable. 如果我在不实现自定义转换器的情况下对其进行序列化,则该文件将不可读。

I implemented MyClassDTO and convertion between MyClass and MyClassDTO . 我实现了MyClassDTO以及MyClassMyClassDTO之间的转换。

MyClassDTO is human readable when using XStream standard serialization. 使用XStream标准序列化时, MyClassDTO是人类可读的。

I want to write XStream Converter serialize and deserialize MyClass . 我想编写XStream Converter序列化和反序列化MyClass
Implementation for Converter.marshal should be following: convert MyClass object to MyClassDTO one and call default serialization for MyClassDTO . Converter.marshal实现应如下:将MyClass对象转换为MyClassDTO然后为MyClassDTO调用默认序列化。

And for Converter.unmarshal : call default deserialization for MyClassDTO object and convert it to MyClass . 对于Converter.unmarshal :调用MyClassDTO对象的默认反序列化并将其转换为MyClass

How to implement such behaviour in simple way? 如何以简单的方式实现这种行为?

I looked through XStream Converter Tutorial , but have not found what I need. 我浏览了XStream Converter教程 ,但没有找到我需要的东西。

I need to fill the stubs below: 我需要填写以下存根:

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

    }
}

Try this, assuming 假设

MatrixDTO m = new MatrixDTO( matrix );

converts from your internal matrix type to the DTO. 从内部矩阵类型转换为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);
}

In the unmarshalling case you may have to insert it manually into the context.currentObject(). 在解组情况下,可能必须将其手动插入context.currentObject()中。 Haven't tried that myself. 自己还没有尝试过。

Hope it helps. 希望能帮助到你。

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

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