I am trying to unmarshall the Json Object which I get back from Restful Service response. But it's throwing an exception while doing unmarshalling?
MyClass.java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyClass
{
@XmlElement(name="id")
private String id;
@XmlElement(name="f-name")
private String fname;
@XmlElement(name="l-name")
private String lname;
// getters and setters for these
}
unmarshal method
JAXBContext context = JAXBContext.newInstance(MyClass.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
URL url = new URL("http://localhost:8080/service-location");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
MyClass myclass=(MyClass)unMarshaller.unmarshal(connection.getInputStream());
And when I tried using some browser client I am getting proper response like below.
[
{
"fname": "JOHN",
"lname": "Doe",
"id": "abc123"
}
]
But I am trying to do Unmarshall in my Client Code it's throwing SAXParserException
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
I not sure what I am doing wrong. Is this way to do unmarshall the JSON object or is there any other way to do it?
UPDATE : SOLUTION
I fixed this by implementing Jackson's ObjectMapper
rather than conventional UnMarshaller
of JAXB
. Here is my Code
ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MYClass.class);
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
list = mapper.readValue(jsonString, type); // JsonString is my response converted into String of json data.