使用 Java 将 JSON 转换为 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36290326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:13:30  来源:igfitidea点击:

Convert JSON into XML using Java

javajsonxml

提问by Rose

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

  }

}

}

回答by Suparna

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>

回答by Vishal--JAVA--CQ

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 repoand add to your library.

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