[英]How to write XStream converter which write and read via converting to intermediate object?
我有一堂課MyClass
。 如果我在不實現自定義轉換器的情況下對其進行序列化,則該文件將不可讀。
我實現了MyClassDTO
以及MyClass
和MyClassDTO
之間的轉換。
使用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.