2013-11-14 131 views
33

我是json的新手。我有一個程序從json對象生成xml。在Java中將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 =「號」,也寫我自己的子元素,比如我自己的屬性。

+0

維諾德,你有沒有對上述問題的解決,「編寫自己的屬性從JSON生成的XML標籤」?我也在尋找解決方案,如果你發現,請在這個帖子中發佈。提前致謝。 – Malleswari

回答

71

從json.org使用(優秀)JSON-Java庫然後

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

toString可以採取第二個參數,以提供XML根節點的名稱。

該庫還能夠使用XML.toJSONObject(java.lang.String string)

檢查Javadoc

鏈接到the github repository

POM

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

原帖更新,以XML轉換成JSON新鏈接

+1

非常感謝。如何寫json對象添加attrubute元素像 vinod

+0

我想唯一的方法是將JSON反序列化爲(自定義)Java對象。然後,使用像XMLBeans或XStream這樣的框架,並在註釋的幫助下指定哪個屬性作爲元素,哪個屬性作爲屬性 –

+0

或者,使用上面簡單的兩行中的XML並將XSLT應用到它 –

0

如果你想更換任何節點值,你可以像這樣

JSONObject json = new JSONObject(str); 
String xml = XML.toString(json); 
xml.replace("old value", "new value"); 
0

用XSLT 3.0轉化爲做到這一點,據我可以告訴的唯一正確方法。它保證能夠生成有效的XML,並且具有良好的結構。 https://www.w3.org/TR/xslt/#json

0

存在underscore-lodash庫,其靜態方法fromJson和toXml。

代碼示例:

import com.github.underscore.lodash.$; 
import java.util.Map; 
import org.junit.Test; 
import static org.junit.Assert.assertEquals; 

public class StringTest { 

    @SuppressWarnings("unchecked") 
    @Test 
    public void toXmlFromJson() { 
     final String json = "{\n" 
      + " \"root\": {\n" 
      + " \"FirstItem\": \"1\",\n" 
      + " \"SecondItem\": \"2\"\n" 
      + " }\n" 
      + "}"; 
     assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n" 
      + " <FirstItem>1</FirstItem>\n <SecondItem>2</SecondItem>\n</root>", 
      $.toXml((Map<String, Object>) $.fromJson(json))); 
    } 
}