2011-10-11 78 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放到你的类路径中。