Search code examples
javaxstream

XStream can't alias fieldnames on deserialization to java


How does this make any sense? I provide an alias for "name", but it still doesn't work. I'm using XStream 1.4.5

com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field B.status

    public class B {
        public String name;
    }

    public static void main(String[] args) {
        XStream serializer = new XStream();
        serializer.alias("a", B.class);
        serializer.aliasField("status", String.class, "name");
        B obj = (B) serializer.fromXML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><a><status>true</status></a>");
    }

Solution

  • The second parameter to aliasField should be the type that declares the field being aliased, not the type of the field.

    serializer.aliasField("status", B.class, "name");