使用Java将JSON转换为XML

时间:2022-04-07 22:49:35

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:

我正在尝试将JSON转换为XML。但是我收到一个org.json无法解决的错误。我还导入了外部jar文件java-json.jar。下面是我的java代码:

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);

  }

}

}

2 个解决方案

#1


4  

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

你的申请没问题。您需要有一个格式良好的JSON对象。

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>

#2


0  

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

你的问题与jar有关。您需要导入org.json包才能使XML方法起作用。

if you are using maven try:

如果你正在使用maven尝试:

<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.

或者从这个maven repo下载jar并添加到你的库中。

#1


4  

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

你的申请没问题。您需要有一个格式良好的JSON对象。

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>

#2


0  

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

你的问题与jar有关。您需要导入org.json包才能使XML方法起作用。

if you are using maven try:

如果你正在使用maven尝试:

<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.

或者从这个maven repo下载jar并添加到你的库中。