Pearl
Pearl

Reputation: 333

Simplest method to Convert Json to Xml

I have web-service in .net. When I retrieve data from database, it returns JSON File in Android Mobile. How can I convert JSON File to XML Or text.

Upvotes: 15

Views: 57996

Answers (5)

Valentyn Kolesnikov
Valentyn Kolesnikov

Reputation: 2097

Underscore-java library has static method U.jsonToXml(string). Live example

import com.github.underscore.U;

public class MyClass {
    public static void main(String[] args) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.jsonToXml(json)); 
    }
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<Price>
  <LineItems>
    <LineItem>
      <UnitOfMeasure>EACH</UnitOfMeasure>
      <Quantity number="true">2</Quantity>
      <ItemID>ItemID</ItemID>
    </LineItem>
  </LineItems>
  <Currency>USD</Currency>
  <EnterpriseCode>EnterpriseCode</EnterpriseCode>
</Price>

Upvotes: 0

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

Standard org.json.XML class converts between JSON and XML in both directions. There is also tutorial on how to use it.

The conversion is not very nice as it does not create XML attributes at all (entities only), so XML output is more bulky than could possibly be. But it does not require to define Java classes matching the data structures that need to be converted.

Upvotes: 1

gil.fernandes
gil.fernandes

Reputation: 14611

Here is an example of how you can do this, generating valid XML. I also use the Jackson library in a Maven project.

Maven setup:

<!-- https://mvnrepository.com/artifact/com.fasterxml/jackson-xml-databind -->
    <dependency>
        <groupId>com.fasterxml</groupId>
        <artifactId>jackson-xml-databind</artifactId>
        <version>0.6.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>

Here is some Java code that first converts a JSON string to an object and then converts the object with the XMLMapper to XML and also removes any wrong element names. The reason for replacing wrong characters in XML element names is the fact that you can use in JSON element names like $oid with characters not allowed in XML. The Jackson library does not account for that, so I ended up adding some code which removes illegal characters from element names and also the namespace declarations.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.xml.XmlMapper;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Converts JSON to XML and makes sure the resulting XML 
 * does not have invalid element names.
 */
public class JsonToXMLConverter {

    private static final Pattern XML_TAG =
            Pattern.compile("(?m)(?s)(?i)(?<first><(/)?)(?<nonXml>.+?)(?<last>(/)?>)");

    private static final Pattern REMOVE_ILLEGAL_CHARS = 
            Pattern.compile("(i?)([^\\s=\"'a-zA-Z0-9._-])|(xmlns=\"[^\"]*\")");

    private ObjectMapper mapper = new ObjectMapper();

    private XmlMapper xmlMapper = new XmlMapper();

    String convertToXml(Object obj) throws IOException {
        final String s = xmlMapper.writeValueAsString(obj);
        return removeIllegalXmlChars(s);
    }

    private String removeIllegalXmlChars(String s) {
        final Matcher matcher = XML_TAG.matcher(s);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            String elementName = REMOVE_ILLEGAL_CHARS.matcher(matcher.group("nonXml"))
                    .replaceAll("").trim();
            matcher.appendReplacement(sb, "${first}" + elementName + "${last}");
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    Map<String, Object> convertJson(String json) throws IOException {
        return mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
    }

    public String convertJsonToXml(String json) throws IOException {
        return convertToXml(convertJson(json));
    }
}

Here is a JUnit test for convertJsonToXml:

@Test
void convertJsonToXml() throws IOException, ParserConfigurationException, SAXException {
    try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/customer_sample.json")) {
        String json = new Scanner(in).useDelimiter("\\Z").next();
        String xml = converter.convertJsonToXml(json);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
        Node first = doc.getFirstChild();
        assertNotNull(first);
        assertTrue(first.getChildNodes().getLength() > 0);
    }
}

Upvotes: 6

Programmer Bruce
Programmer Bruce

Reputation: 66943

For a simple solution, I recommend Jackson, as it can transform arbitrarily complex JSON into XML with just a few simple lines of code.

import org.codehaus.jackson.map.ObjectMapper;

import com.fasterxml.jackson.xml.XmlMapper;

public class Foo
{
  public String name;
  public Bar bar;

  public static void main(String[] args) throws Exception
  {
    // JSON input: {"name":"FOO","bar":{"id":42}}
    String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}";

    ObjectMapper jsonMapper = new ObjectMapper();
    Foo foo = jsonMapper.readValue(jsonInput, Foo.class);

    XmlMapper xmlMapper = new XmlMapper();
    System.out.println(xmlMapper.writeValueAsString(foo));
    // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo>
  }
}

class Bar
{
  public int id;
}

This demo uses Jackson 1.7.7 (the newer 1.7.8 should also work), Jackson XML Databind 0.5.3 (not yet compatible with Jackson 1.8), and Stax2 3.1.1.

Upvotes: 12

N-JOY
N-JOY

Reputation: 7635

No direct conversion API is available in android to convert JSON to XML. You need to parse JSON first then you will have to write logic for converting it to xml.

Upvotes: 1

Related Questions