如何在java中将XML转换为JSON?

sel*_*rai 2 java xml json

如何在java servlet中将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 ); 
Run Code Online (Sandbox Code Playgroud)

请帮我.

Ger*_*rre 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 在@ antur123的回答中,我相信"string"的所有实例都应该是"String",在这种情况下代码应该有效. (3认同)