Koushik M
Koushik M

Reputation: 11

JSON String to JAXB java object unmarshalling

Simple Spring boot app.

I have a JSON String which needs to be converted to XML and that XML needs to be un marshalled to a java pojo which has JAXB annotations.

String response = "JSON FORMATTED STRING";
JSONObject json = new JSONObject(response);
String xml = XML.toString(json);//prints valid XML. no UTF stmt.
Unmarshaller jaxbUnmarshaller = 
   JAXBContext.newInstance(JAXBPOJO.class).createUnmarshaller();
jaxbUnmarshaller.unmarshal(new StringReader(xml));

The error I'm getting is below. Trying to understand why I'm getting this error .

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Message"). Expected elements are <{http://SOAP_WSDL_URL}JAXb_POJO_NAME>
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:714)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:232)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:227)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:94)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1119)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:544)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:526)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:138)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)

The SOAP WSDL URL in the error is another web service int he spring boot APp. Trying to understand why this is showing up in the error.

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Message"). Expected elements are <{http://SOAP_WSDL_URL}JAXb_POJO_NAME>

Upvotes: 1

Views: 3080

Answers (1)

locus2k
locus2k

Reputation: 2935

Instead of going from json to xml to pojo you can go directly from json to the pojo using jackson:

ObjectMapper objectMapper = new ObjectMapper();
JAXBPOJO pojo = objectMapper.readValue(response, JAXBPOJO.class);

If you want to ignore unknown properties add this annotation to your pojo class:

@JsonIgnoreProperties(ignoreUnknown = true)

If you can't add it to the pojo then you can add this setting:

ObjectMapper objectMapper = new ObjectMapper()
  .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Make sure to add the dependency if using maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>

https://github.com/FasterXML/jackson

Upvotes: 2

Related Questions