SimpleXML enum case-sensitivity

前提是你 提交于 2019-12-04 14:46:29

After some investigation of the source code, i have discovered that the library uses interface Transform to transform values to Strings. The default behavior of enum transformations is defined by class EnumTransform. In order to customize that, you can define you own Transform class. The following version of Transform implementation would call toString() instead of the default name() on the enum objects.

class MyEnumTransform implements Transform<Enum> {
    private final Class type;

    public MyEnumTransform(Class type) {
        this.type = type;
    }

    public Enum read(String value) throws Exception {
        for (Object o : type.getEnumConstants()) {
            if (o.toString().equals(value)) {
                return (Enum) o;
            }
        }
        return null;
    }

    public String write(Enum value) throws Exception {
        return value.toString();
    }
}

Transform objects are returned from match method by objects of Matcher interface. There could be several Matcher objects. The library tries them one by one until it finds one that returns a non-null Transformer object. You can define your own Matcher object and pass it as argument to the constructor of Persister class. This object will get the highest priority.

Persister serializer = new Persister(new Matcher() {
    public Transform match(Class type) throws Exception {
        if (type.isEnum()) {
            return new MyEnumTransform(type);
        }
        return null;
    }
 });

Finally, you wont forget to define a toString method on your enum classes. Then the combination of codes above will do you the work of encoding enum objects using their toString values.

You should override toString()

@Override 
public String toString() {
       return this.value.toLowerCase();
}

Then write results using

serializer.write(example.toString(), result);

I would look at the serializer code and undestand what that is doing, as you have not annotated any of your fields...which (according to their docs) should throw an an exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!