如何编写XStream转换器,通过转换为中间对象进行读写?
我有一个类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
}
}
I have a class MyClass
. If I serialize it without implementing custom converter it is not human readable.
I implemented MyClassDTO
and convertion between MyClass
and MyClassDTO
.
MyClassDTO
is human readable when using XStream standard serialization.
I want to write XStream Converter serialize and deserialize MyClass
.
Implementation for Converter.marshal
should be following: convert MyClass
object to MyClassDTO
one and call default serialization for MyClassDTO
.
And for Converter.unmarshal
: call default deserialization for MyClassDTO
object and convert it to MyClass
.
How to implement such behaviour in simple way?
I looked through XStream Converter Tutorial, but have not found what I need.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设
从内部矩阵类型转换为 DTO,请尝试此操作。
在解组情况下,您可能必须手动将其插入到 context.currentObject() 中。我自己没试过。
希望有帮助。
Try this, assuming
converts from your internal matrix type to the DTO.
In the unmarshalling case you may have to insert it manually into the context.currentObject(). Haven't tried that myself.
Hope it helps.