【问题标题】:How to write XStream converter which write and read via converting to intermediate object?如何编写通过转换为中间对象进行读写的XStream转换器?
【发布时间】:2012-02-15 01:57:16
【问题描述】:

我有一堂课MyClass。如果我在不实现自定义转换器的情况下对其进行序列化,则它是不可读的。

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

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

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

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

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

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

我需要填写下面的存根:

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

    }
}

【问题讨论】:

  • 你能把你的程序和战术贴出来吗...
  • 哪个程序和哪个策略?
  • 我的意思是你应该发布你正在尝试的代码示例......
  • 我添加了有问题的存根,希望它能让我的问题更清楚。谢谢。

标签: java xml xml-serialization xstream


【解决方案1】:

试试这个,假设

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

希望对你有帮助。

【讨论】:

  • 似乎是正确的。但我没有尝试过,因为已经以其他方式实施。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2011-10-08
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多