I am getting a response from server as XML. But I need to display this in JSON format.
Is there any way to convert it without any third party API? I used Jackson but
You can do that with Jackson and no POJOs are required for that:
String xml = "\n" +
"\n" +
" \n" +
" 400 \n" +
" The field 'quantity' is invalid. \n" +
" \n" +
" The quantity specified is greater than the quantity of the product that is available to ship. \n" +
" 0 \n" +
" 12525 \n" +
" \n" +
" \n" +
" ";
XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(xml.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
The following dependencies are required:
com.fasterxml.jackson.core
jackson-core
2.8.2
com.fasterxml.jackson.core
jackson-databind
2.8.2
com.fasterxml.jackson.core
jackson-annotations
2.8.2
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.8.2
Be aware of the XmlMapper limitations stated in the documentation:
Tree Model is only supported in limited fashion: specifically, Java arrays and
Collectionscan be written, but can not be read, since it is not possible to distinguish Arrays and Objects without additional information.
You also can do it with JSON.org:
String xml = "\n" +
"\n" +
" \n" +
" 400 \n" +
" The field 'quantity' is invalid. \n" +
" \n" +
" The quantity specified is greater than the quantity of the product that is available to ship. \n" +
" 0 \n" +
" 12525 \n" +
" \n" +
" \n" +
" ";
String json = XML.toJSONObject(xml).toString();
The following dependency is required:
org.json
json
20160810