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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7724263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:08:06  来源:igfitidea点击:

how to convert XML to JSON in java?

javaxmljson

提问by selladurai

How to convert XML to JSON in java servlet.

如何在 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 ); 

please help me.

请帮我。

回答by German Latorre

You can grab a set of Java classes to handle JSON at http://json.org/java/

您可以在http://json.org/java/获取一组 Java 类来处理 JSON

There you can find the XML and JSONObject classes, among others. This code could work for you:

在那里您可以找到 XML 和 JSONObject 类等。此代码可以为您工作:

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

回答by user1515918

You need to import org.json.XML in your class to resolve XML. Or Put org.json.XML to your classpath.

您需要在类中导入 org.json.XML 来解析 XML。或者把 org.json.XML 放到你的类路径中。