gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:33:18 26 4
gpt4 key购买 nike

我有一个类MyClass。如果我在不实现自定义转换器的情况下序列化它,它就不是人类可读的。

我实现了 MyClassDTO 以及 MyClassMyClassDTO 之间的转换。

MyClassDTO 在使用 XStream 标准序列化时是人类可读的。

我想编写XStream Converter序列化和反序列化MyClass
Converter.marshal 的实现应如下所示:将 MyClass 对象转换为 MyClassDTO 并调用 MyClassDTO 的默认序列化。

对于 Converter.unmarshal :调用 MyClassDTO 对象的默认反序列化并将其转换为 MyClass

如何以简单的方式实现这种行为?

我浏览了XStream Converter Tutorial ,但还没有找到我需要的东西。

我需要填写以下 stub :

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() 中。我自己没试过。

希望有帮助。

关于java - 如何编写XStream转换器,通过转换为中间对象进行读写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9286918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com