我有以下课程。
class SimpleDate {
private final int year; /* ? */
private final int month; /* 0 ~ 11 */
private final int date; /* 1 ~ 31 */
}
现在,我打算将课程重新考虑到。
class SimpleDate {
private final int year; /* ? */
private final int month; /* 1 ~ 12!!!!! <-- change from 0 based to 1 based */
private final int day; /* 1 ~ 31 */
}
要解决变量重命名问题,我将使用别名。
xStream.aliasField("date", SimpleDate.class, "day");
但是,我怎么知道我正在阅读一个旧的XML文件,我将为新读取的月份字段+1,将其从0更改为基于1?
答案 0 :(得分:3)
xstream常见问题解答http://x-stream.github.io/faq.html有一节介绍tp如何处理不同版本。
答案 1 :(得分:1)
// Converter used to make sure XStream still able to read old version of XML
// files.
private static Converter getSimpleDateConverter() {
return new Converter() {
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) {
SimpleDate simpleDate = (SimpleDate) o;
writer.startNode("year");
writer.setValue("" + simpleDate.getYear());
writer.endNode();
writer.startNode("month");
writer.setValue("" + simpleDate.getMonth());
writer.endNode();
writer.startNode("day");
writer.setValue("" + simpleDate.getDay());
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
Map<String, String> map = new HashMap<String, String>();
while (reader.hasMoreChildren()) {
reader.moveDown();
map.put(reader.getNodeName(), reader.getValue());
reader.moveUp();
}
// Introduce since version 1.0.6.
// We had renamed 'date' field to 'day' field.
final boolean isOldVersion = map.containsKey("date");
if (isOldVersion) {
final int year = Integer.parseInt(map.get("year"));
// We changed 0 based month to 1 based month, to fit into Joda library.
final int month = Integer.parseInt(map.get("month")) + 1;
final int day = Integer.parseInt(map.get("date"));
return new SimpleDate(year, month, day);
} else {
final int year = Integer.parseInt(map.get("year"));
final int month = Integer.parseInt(map.get("month"));
final int day = Integer.parseInt(map.get("day"));
return new SimpleDate(year, month, day);
}
}
@Override
public boolean canConvert(Class type) {
return SimpleDate.class.isAssignableFrom(type);
}
};
}
xStream.registerConverter(getSimpleDateConverter());