Rose
Rose

Reputation: 1498

Convert JSON into XML using Java

I'm trying to convert JSON into XML. But I'm getting an error that org.json cannot be resolved. I have also imported the external jar file java-json.jar. Below is my java code:

import org.json.JSONObject;
public class JsontoXML{
  public static void main(String args[])
  {
    String str ={'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested' {'id':42},'array':[1,2,3]}"; 
    JSONObject json = new JSONObject(str);
    String xml = XML.toString(json);
    System.out.println(xml);

  }

}

Upvotes: 4

Views: 21841

Answers (3)

Valentyn Kolesnikov
Valentyn Kolesnikov

Reputation: 2097

Underscore-java can convert json to xml:

String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\": {\"id\":42},"
    + "\"array\":[1,2,3]}";
String xml = U.jsonToXmlMinimum(json);
System.out.println(xml);

output:

<root>
  <name>JSON</name>
  <integer>1</integer>
  <double>2.0</double>
  <boolean>true</boolean>
  <nested>
    <id>42</id>
  </nested>
  <array>1</array>
  <array>2</array>
  <array>3</array>
</root>

Upvotes: 0

Vishal--JAVA--CQ
Vishal--JAVA--CQ

Reputation: 188

Your issue is related to jar. You need to import the org.json package for the XML methods to work.

if you are using maven try:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Or else download the jar from this maven repo and add to your library.

Upvotes: 0

Suparna
Suparna

Reputation: 1182

Your application is alright. You need to have a well formed JSON object.

Source Code

package algorithms;

import org.json.JSONObject;
import org.json.XML;
public class JsonToXML{
public static void main(String args[])
{
    JSONObject json = new JSONObject("{name: JSON, integer: 1, double: 2.0, boolean: true, nested: { id: 42 }, array: [1, 2, 3]}");

    String xml = XML.toString(json);
    System.out.println(xml);

  }
}

Check with the example above.

Output:

<boolean>true</boolean><array>1</array><array>2</array><array>3</array><double>2.0</double><name>JSON</name><integer>1</integer><nested><id>42</id></nested>

Upvotes: 5

Related Questions