无法转换包含“&”或“;”的 XML 字符串到 JSON 个对象

Unable to convert XML string containing '&' or ';' to JSON object

我想将 XML 字符串转换为 JSON 对象。

下面是XML:

<request>
    <Products>
        <Product>
            <ProductName>H &amp; M</ProductName>
            <quantity>1</quantity>
            <totalProductCost>17.03</totalProductCost>
        </Product>
    </Products>
</request>

此 XML 字符串作为请求参数出现。 httpReqMap 是包含请求参数及其值的映射。 当我执行这条语句时

String reqstring = httpReqMap.get("request");

将 XML 字符串分成两部分。因此 XML 无效,我无法将其转换为 JSON 对象。

我尝试将“&”作为“&”传递。

代码如下:

String reqstring = httpReqMap.get("request");
JSONObject jsonObject = XML.toJSONObject(httpReqMap.get("request"));

它应该转义特殊字符并将XML转换为JSON。

我认为您最好的选择是将 XML 作为 POST 查询的有效负载传递,而不是在 URL.

中传递

如果你真的想要这样做,你必须url-encode整个xml。关于这个主题有很多问题,例如 Java URL encoding of query string parameters.