Reputation: 10974
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
}
}
Upvotes: 0
Views: 596
Reputation: 1996
Try this, assuming
MatrixDTO m = new MatrixDTO( matrix );
converts from your internal matrix type to the 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(). Haven't tried that myself.
Hope it helps.
Upvotes: 2