2014-01-13 140 views
0

我正在編寫一個代碼,將我的JSON轉換爲XML。轉換代碼是:將JSON轉換爲XML的問題

 BufferedReader in; 
     try { 
      InputStream is = new FileInputStream("/Users/appleBud/json"); 

     jsonData = IOUtils.toString(is); 

     System.out.println("json data is: "+jsonData); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 



     XMLSerializer serializer = new XMLSerializer(); 
     JSON json = JSONSerializer.toJSON(jsonData); 

     String xml = serializer.write(json); 
     System.out.println(xml); 

我能夠生成XML。但是,我的JSON包含無法以各自格式顯示的HTML代碼。例如,'<'變成& lt和'>'在我的XML中變成'& gt'。我試圖使用不同的解決方案,但沒有解決我的問題。

我的JSON是一樣的東西:

{ 
    "title":"<p>This is demo </p>", 
    "index":"<li>Demo1</li><li>Demo2</li>", 
    "name": "KB649364539", 
    "creationDate": "Wed Aug 07 2013 00:00:52 GMT+0000" 
} 

,併產生相應的XML是:

<title type="string">&lt;p&gt;This is demo&lt;/p&gt;</title> 
<index type="string">&lt;li&gt;Demo1&lt;/li&gt;&lt;li&gt;Demo2&lt;/li&gt;</index> 

預期成果是:

<title><p>This is demo</p></title> 
<index><li>Demo1</li><li>Demo2</li></index> 

有什麼辦法,我可以做到這一點?

+0

那麼你的Json看起來像什麼? – Jason

+1

'<'變成'<'和'>'變成'>'**這不是一個錯誤**,這就是它如何顯示爲 – TwilightSun

+0

爲什麼不將Json轉換爲Java對象然後將其轉換爲XML?您可以輕鬆控制內容。 – elbuild

回答

1

只需更換HTML轉義字符,它會正常工作:)

public static String filterDecode(String url){ 

    url = url.replaceAll("&amp;", "&") 
    .replaceAll("&lt;", "<") 
    .replaceAll("&gt;", ">") 
    .replaceAll("&apos;", "\'") 
    .replaceAll("&quot;", "\"") 
    .replaceAll("&nbsp;", " ") 
    .replaceAll("&copy;", "@") 
    .replaceAll("&reg;", "?"); 
    return url; 
} 
+0

感謝@Bob。它的工作,但面臨另一個問題。我的XML只是創建了一個標籤,如。你能幫我解決這個問題嗎?我不希望該類型成爲我的標籤的一部分。 – AppleBud

+0

我建議您將一些XML操作API集成到您的項目中,例如DOM4J,SAX。通常它爲DOM操作提供了許多方便的方法。否則你將不得不更換和更換。 –

0

我建議你使用JSON.org,這是很容易使用只是這樣做:

import org.json.XML; 
import org.json.JSONException; 
import org.json.JSONObject; 

JSONObject jsonObj = new JSONObject(your string or file *.json); 
System.out.println(XML.toString(jsonObj);