Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xstream and Enum Unmarshalling : No enum constant

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..

like image 452
LB40 Avatar asked Oct 03 '12 15:10

LB40


2 Answers

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);
like image 72
ysl Avatar answered Sep 29 '22 07:09

ysl


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());
like image 20
dtelaroli Avatar answered Sep 29 '22 08:09

dtelaroli