Search code examples
javaxstream

XStream returns attribute value as null


Today I faced strange behavior of XStream. So, XML:

<AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>

Java class:

@XStreamAlias("AddressObjectType")
public class AddressObjectType {

    @XStreamAsAttribute
    @XStreamAlias("KOD_T_ST")
    private Integer id;

    @XStreamAsAttribute
    @XStreamAlias("SOCRNAME")
    private String name;

    @XStreamAsAttribute
    @XStreamAlias("SCNAME")
    private String shortName;

    @XStreamAsAttribute
    @XStreamAlias("LEVEL")
    private int level;
    // . . . getters, setters
}

I have problem with only attribute KOD_T_ST. During deserialization always throws com.thoughtworks.xstream.converters.ConversionException and cause is NullPointerException. Attribute value is always null. Even I switch type from Integer to String. What is going on? Does XStream has any limitations for alias names? How to read value?

XStream version 1.4.11.1.

Many thanks for your help and best regards.


Solution

  • There is a problem with your existing xml string

    <AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>
    

    Instead of using the above, use the below one, it will work, there is no change in the AddressObjectType object model. Mark the difference, there is double underscore(__) in the xml which I provided.

    <AddressObjectType KOD__T__ST="0" LEVEL="0" SOCRNAME="blabla"/>
    

    To understand, refer below the link. http://x-stream.github.io/faq.html#XML_double_underscores

    To quote,

    Why do field names suddenly have double underscores in the generated XML? XStream maps Java class names and field names to XML tags or attributes. Unfortunately this mapping cannot be 1:1, since some characters used for identifiers in Java are invalid in XML names. Therefore XStream uses an XmlFriendlyNameCoder to replace these characters with a replacement. By default this NameCoder uses an underscore as escape character and has therefore to escape the underscore itself also. You may provide a different configured instance of the XmlFriendlyNameCoder or a complete different implementation like the NoNameCoder to prevent name coding at all. However it is your responsibility then to ensure, that the resulting names are valid for XML.