我正在序列化一个包含enum作为字段的类,比方说:
private class DayOfWeekSet {
private final EnumSet<DayOfWeek> days;
}
public enum DayOfWeek implements Serializable {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
枚举的Xstream输出是:
<days>
<day enum-type="com.company.model.DayOfWeek">MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY</day>
</days>
我想要像:
<days>
<day>MONDAY</day>
<day>TUESDAY</day>
<day>WEDNESDAY</day>
<day>THURSDAY</day>
<day>FRIDAY</day>
<day>SATURDAY</day>
<day>SUNDAY</day>
</days>
我在XStream文档中找到了@XStreamImplicit(itemFieldName =“name”)注释,但它仅适用于Collections。
是否可以使用注释进行操作,还是需要创建转换器?
为了获得我在创建以下转换器之前描述的结果:
public class XstreamDayOfTheWeekEnumConverter implements Converter {
@Override
@SuppressWarnings("rawtypes")
public boolean canConvert(Class type) {
return type.equals(DayOfWeekSet.class);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
DayOfWeekSet set = (DayOfWeekSet) source;
for (Iterator<DayOfWeek> iterator = set.getDays().iterator(); iterator.hasNext();) {
Enum<DayOfWeek> value = iterator.next();
writer.startNode("day");
writer.setValue(value.name());
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
//Not implemented
return null;
}
}
如果我用它注释Enum,有没有办法从xstream别名注释(@XStreamAlias)获取节点名?
答案 0 :(得分:1)
我不认为这在XStream中存在。您可能必须编写自己的转换器。你可以从EnumSetConverter的代码开始,这应该不是很难......
答案 1 :(得分:1)
EnumSetConverter不好用。
如果你可以使用另一个集合,那么工作正常:
public class DayOfWeekSet {
private List<DayOfWeek> days = new ArrayList<DayOfWeek>();
DayOfWeekSet() {
for (DayOfWeek dow: DayOfWeek.values()) {
days.add(dow);
}
}
@XStreamAlias("day")
public enum DayOfWeek implements Serializable {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
}
<DayOfWeekSet>
<days>
<day>MONDAY</day>
<day>TUESDAY</day>
<day>WEDNESDAY</day>
<day>THURSDAY</day>
<day>FRIDAY</day>
<day>SATURDAY</day>
<day>SUNDAY</day>
</days>
</DayOfWeekSet>