我正在序列化一个包含枚举作为字段的类,比如说:
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") 注释,但它仅适用于集合。
是否可以使用注释来做到这一点,还是我需要创建一个转换器?
为了获得我在创建以下转换器之前描述的结果:
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)中获取节点名称?