here's an extract from an XML I'd like to parse :
<node version="1.0.7" errorCode="0" message="">
errorCode is actually a fixed set of constants so I thought it would be a good idea to represent it as an enum :
public enum ErrorCode {
OK (0,"ok"),
ERR (1,"Error"),
BIGERR (2,"Big Error");
private int code;
private String name;
ErrorCode(int code, String name) {...}
}
I don't know how to map the "0" from the xml file with the various constants defined in my enum... I keep on getting a conversion exception with no enum constant :
com.thoughtworks.xstream.converters.ConversionException: No enum constant my.package.ErrorCode.0
I don't know how I could specify an alias for the values...(or if i have to implement my own converter.).
Thanks..
I had the same problem and I have solved it by creating a Converter class.
public class MyEnumConverter implements Converter {
public static MyEnumConverter getInstance() {
return new MyEnumConverter();
}
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
writer.setValue(((MyEnum) value).name());
}
//method that return the enum value by string
//if value equals return the correct enum value
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
return MyEnum.get(reader.getValue()); //method get implemented in enum
}
@SuppressWarnings("rawtypes")
public boolean canConvert(Class clazz) {
return MyEnum.class.isAssignableFrom(clazz);
}
}
don't forget to register the converter
xstream.registerConverter(MyEnumConverter.getInstance());