2011-10-11 33 views
2

如何在java servlet中將XML轉換爲JSON。如何在XML中將XML轉換爲JSON?

<?xml><SOAP-ENV:Envelope xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:HNS="http://tempuri.org/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><HNS:ROClientID SOAP-ENV:mustUnderstand="0">{6C9A8E69-2018-4090-8FA7-DEB98300E102}</HNS:ROClientID></SOAP-ENV:Header><SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ro="http://tempuri.org/"><NS1:GetStationListResponse xmlns:NS1="urn:WOOSServices-WOrbitService"><Stations xsi:type="xsd:string"></Stations><Result xsi:type="xsd:string">{ 
    "MOColmns": [ 
     { 
      "MOTitle": "Description" 
     }, 
     { 
      "MOTitle": "station_name" 
     }, 
     { 
      "MOTitle": "StationID" 
     }, 
     { 
      "MOTitle": "StationINT" 
     } 
    ] 
}</Result></NS1:GetStationListResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>"; 
      String xml = "<xx yy='nn'><mm>zzz</mm></xx>"; 

      JSONArray json = (JSONArray) XMLSerializer.read(xml); 
      System.out.println(json); 

請幫幫我。

+2

爲什麼答案不被接受的任何原因? :-) –

回答

10

您可以在http://json.org/java/

搶了一組Java類來處理JSON的在那裏你可以找到XML和的JSONObject類,等等。此代碼可以爲你工作:

public String XMLtoJSON(String xml) { 
    JSONObject jsonObj = XML.toJSONObject(xml); 
    String json = jsonObj.toString(); 
    return json; 
} 
+3

在@ antur123的回答中,我相信「string」的所有實例都應該是「String」,在這種情況下,該代碼應該可以工作。 – ultrageek

+0

哎呀!謝謝,只是編輯它! –

+0

@selladurai任何理由不選擇這個答案? –

0

您需要在您的類中導入org.json.XML來解析XML。或者把org.json.XML放到你的類路徑中。