Java设置了XStream反序列化规则

时间:2015-11-20 14:59:36

标签: java xml serialization xstream

我提交了一些代码基于enum的课程。我有这个类的xml serealized对象。但是当我尝试用XStream反序列化这个xml时,我收到了:

  

com.thoughtworks.xstream.converters.ConversionException:No enum constant com.functest.util.TriState.0:No enum constant com.functest.util.TriState.0

class Params{
   String clientCode;
   TriState triState;
}

xmlParameters String

<Params>
    <clientCode>1516001</clientCode>
    <triState>0</triState>
</Params>

TriState

enum TriState implements codeBased{
    YES(1);
    NO(0);
    UNDEFINED(-1);

    int code;

    TriState fromCode(int code){
         if(code == 1) return YES;
         if(code == 0) return NO;
         return UNDEFINED;
    }
}

我试着像这样反序列化xml:

XStream xStream = new XStream();
xStream.alias("triState", TriState.class);
Params p = (Params) xStream.fromXML(xmlParameters);

如何设置反序列化规则以从xml获取值并调用枚举方法fromCode(0)

1 个答案:

答案 0 :(得分:0)

将你的fromCode转换为静态方法:

public enum TriState {
    YES(1),NO(0),UNDEFINED(-1);
    int code;
    private TriState(int code) {
        this.code = code;
    }
    public static TriState fromCode(int code) {
        if (code == 1)
            return YES;
        if (code == 0)
            return NO;
        return UNDEFINED;
    }
}

定义一个使用静态方法将代码转换为有效枚举的转换器:

public class TriStateConverter implements Converter {
    public boolean canConvert(Class type) {
        return TriState.class==type;
    }
    public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) {
        writer.setValue(Integer.toString(((TriState)o).code));
    }
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
        return TriState.fromCode(Integer.parseInt(reader.getValue()));
    }
}

没有尝试过代码,但应该可以使用。