0

我正在序列化一个包含枚举作为字段的类,比如说:

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)中获取节点名称?

4

2 回答 2

1

我认为这在 XStream 中不存在。您可能必须编写自己的转换器。您可以从EnumSetConverter的代码开始,这应该不是很困难...

于 2010-09-29T12:46:03.060 回答
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>
于 2010-09-30T16:57:27.837 回答