如何使用XStream有条件地序列化字段(属性)

时间:2011-02-17 20:56:01

标签: xml-serialization xstream

我正在使用XStream来序列化和反序列化对象。例如,名为Rating的类定义如下:

Public Class Rating {

  String id;
  int score;
  int confidence;

  // constructors here...
}

但是,在此课程中,变量confidence是可选的。

因此,当置信度值(非0)时,Rating对象的XML表示应如下所示:

<rating>
<id>0123</id>
<score>5</score>
<confidence>10</confidence>
</rating>

但是,当置信度未知(默认值为0)时,置信度 应该从XML表示中省略属性:

<rating>
<id>0123</id>
<score>5</score>
</rating>

有人能告诉我如何使用XStream有条件地序列化字段吗?

1 个答案:

答案 0 :(得分:6)

一种选择是写一个converter

这是我很快为你写的:

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class RatingConverter implements Converter
{

    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(Rating.class);
    }

    @Override
    public void marshal(Object value, HierarchicalStreamWriter writer,
            MarshallingContext context) 
    {
        Rating rating = (Rating) value;

        // Write id
        writer.startNode("id");
        writer.setValue(rating.getId());
        writer.endNode();

        // Write score
        writer.startNode("score");
        writer.setValue(Integer.toString(rating.getScore()));
        writer.endNode();

        // Write confidence
        if(rating.getConfidence() != 0)
        {
            writer.startNode("confidence");
            writer.setValue(Integer.toString(rating.getConfidence()));
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader arg0,
            UnmarshallingContext arg1)
    {
        return null;
    }
}

剩下要做的就是注册转换器,并在Rating等级中提供访问器方法(即getId,getScore,getConfidence)。

注意:您的另一个选择是适当地omit the field