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 have done this with EnumToStringConverter
Map<String, ErrorCode> map = new HashMap<>();
map.put(ErrorCode.OK.getCode(), Error.OK);
map.put(ErrorCode.ERR.getCode(), Error.ERR);
map.put(ErrorCode.BIGERR.getCode(), Error.BIGERR);
xstream.registerConverter(new EnumToStringConverter<>(ErrorCode.class, map);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With