在 Java 中将 JSON 转换为 XML

新手上路,请多包涵

我是 json 的新手。我有一个从 json 对象生成 xml 的程序。

 String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
    JSON json = JSONSerializer.toJSON( str );
    XMLSerializer xmlSerializer = new XMLSerializer();
    xmlSerializer.setTypeHintsCompatibility( false );
    String xml = xmlSerializer.write( json );
    System.out.println(xml);

输出是:

 <?xml version="1.0" encoding="UTF-8"?>
<o><array json_class="array"><e json_type="number">1</e><e json_type="number">2</e><e json_type="number">3</e></array><boolean json_type="boolean">true</boolean><double json_type="number">2.0</double><integer json_type="number">1</integer><name json_type="string">JSON</name><nested json_class="object"><id json_type="number">42</id></nested></o>

我最大的问题是如何编写我自己的属性而不是 json_type=“number” 以及如何编写我自己的子元素,如 .

原文由 vinod 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 707
2 个回答

然后使用来自 json.org 的(优秀的)JSON-Java 库

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString 可以采用第二个参数来提供 XML 根节点的名称。

该库还能够使用 XML.toJSONObject(java.lang.String string) 将 XML 转换为 JSON

检查 Javadoc

链接到 github 存储库

聚甲醛

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

原始帖子更新了新链接

原文由 Bruno Grieder 发布,翻译遵循 CC BY-SA 3.0 许可协议

Underscore -java 库有静态方法 U.jsonToXml(jsonstring)实例

import com.github.underscore.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
        System.out.println(json);
        String xml = U.jsonToXml(json);
        System.out.println(xml);
    }
}

输出:

 {"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name>JSON</name>
  <integer number="true">1</integer>
  <double number="true">2.0</double>
  <boolean boolean="true">true</boolean>
  <nested>
    <id number="true">42</id>
  </nested>
  <array number="true">1</array>
  <array number="true">2</array>
  <array number="true">3</array>
</root>

原文由 Valentyn Kolesnikov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题