簡體   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