猿问

在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”,以及如何编写自己的子元素,例如。


MYYA
浏览 287回答 3
3回答

尚方宝剑之说

Underscore-java库具有静态方法U.jsonToXml(jsonstring)。我是该项目的维护者。现场例子import com.github.underscore.lodash.U;public class MyClass {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(json);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; String xml = U.jsonToXml(json);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(xml);&nbsp;&nbsp; &nbsp; }}输出:{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}<?xml version="1.0" encoding="UTF-8"?><root>&nbsp; <name>JSON</name>&nbsp; <integer number="true">1</integer>&nbsp; <double number="true">2.0</double>&nbsp; <boolean boolean="true">true</boolean>&nbsp; <nested>&nbsp; &nbsp; <id number="true">42</id>&nbsp; </nested>&nbsp; <array number="true">1</array>&nbsp; <array number="true">2</array>&nbsp; <array number="true">3</array></root>
随时随地看视频慕课网APP

相关分类

Java
我要回答