I’m putting together a Java client for Bing Translate, using their REST API. I can authenticate with OAuth and run translations with no problem, unmarshalling those simple String responses into JAXB objects with no problem.
However, when it comes to more complex types, I’m struggling to work out why I’m constantly getting a null value on the field of my Java object. The response I get from the service is:
<ArrayOfstring
xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<string>ar</string>
<string>bg</string>
<string>ca</string>
<string>zh-CHS</string>
<string>zh-CHT</string>
</ArrayOfstring>
I’m unmarshalling the object using the following method:
@SuppressWarnings("unchecked")
public static <T extends Object> T unmarshallObject(Class<T> clazz, InputStream stream)
{
T returnType = null;
try
{
JAXBContext jc = JAXBContext.newInstance(clazz);
Unmarshaller u = jc.createUnmarshaller();
returnType = (T) u.unmarshal(stream);
} catch (Exception e1)
{
e1.printStackTrace();
}
return returnType;
}
Which works fine for simple objects, so I suspect the problem lies within my annotations for the complex object I’m trying to generate. The code for that is:
package some.package;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ArrayOfstring", namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays")
public class ArrayOfString implements Serializable
{
@XmlElement(name="string", namespace="http://schemas.microsoft.com/2003/10/Serialization")
private List<String> string;
public List<String> getString()
{
return string;
}
public void setString(List<String> strings)
{
this.string = strings;
}
}
In desperation, I replaced the @XmlElement(name=”string”) with @XmlAnyElement and I got a List of Strings back, but no values.
So, my question is – what needs to change for the above XML to be interpretted correctly, and more importantly why?
In your example, your
stringelements actually belong to thehttp://schemas.microsoft.com/2003/10/Serialization/Arraysnamespace.Your annotation says you expect the
http://schemas.microsoft.com/2003/10/Serializationnamespace.Try
instead.