【问题标题】:how to convert XML to JSON in java?如何在java中将XML转换为JSON?
【发布时间】:2011-10-11 09:57:47
【问题描述】:

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

请帮帮我。

【问题讨论】:

  • 答案不被接受的任何原因? :-)

标签: java xml json


【解决方案1】:

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

您可以在其中找到 XML 和 JSONObject 类等。此代码可能适合您:

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

【讨论】:

  • 在@antur123 的回答中,我相信“string”的所有实例都应该是“String”,在这种情况下,代码应该可以工作。
  • @selladurai 有什么原因没有选择这个作为答案吗?
  • 出色的观察,@RajeevM,:-)
  • 嗨 antur123,我无法处理 XML.toJSONObject(xml),因为我可以解析 XML,我该如何解决这个问题?请帮帮我。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    Underscore-java可以将xml转json。

    import com.github.underscore.U;
    
    String xml = "<xx yy=\"nn\"><mm>zzz</mm></xx>";
    
    String json = U.xmlToJson(xml);  
    System.out.println(json);
    

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 2013-06-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2013-01-28
      相关资源
      最近更新 更多