我正在使用XStream来序列化和反序列化对象.例如,名为Rating的类定义如下: Public Class Rating { String id; int score; int confidence; // constructors here...} 但是,在此类中,变量置信度是可选的. 因此,当置
Public Class Rating { String id; int score; int confidence; // constructors here... }
但是,在此类中,变量置信度是可选的.
因此,当置信度值已知(非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有条件地序列化字段?
一种选择是写一个 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.