Web Services 如何从Json字符串中删除双引号““

gj3fmq9x  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(235)

在JSON响应中,下面的**'data'**字段会出现双引号,如下所示-

{
"bID" : 1000013253,
"bTypeID" : 1,
"name" : "Test1"
"data" : "{"bc": {    "b": {        "t": 1,        "r": 1,        "c": "none"    },    "i": "CM19014269"}}"
}

验证此JSOn时,收到如下验证错误

Error: Parse error on line 18:
...   "document" : "[{"bc": {    "b": {    
-----------------------^
Expecting 'EOF', '}', ':', ',', ']'

我希望JSON响应显示为-

{
"bID" : 1000013253,
"bTypeID" : 1,
"name" : "Test1"
"data" : {"bc": {    "b": {        "t": 1,        "r": 1,        "c": "none"    },    "i": "CM19014269"}}
}

我使用的服务器端代码是-

{
    for (ManageBasketTO manageBasketTO : retList) {
        Long basketId = manageBasketTO.getBasketID();
        BasketTO basketTo = null;
        basketTo = CommonUtil.getBasket(usrCtxtObj, basketId, language, EBookConstants.FOR_VIEWER_INTERFACE,
                usrCtxtObj.getScenarioID(), EBookConstants.YES, request, deviceType);
        String doc = Utilities.getStringFromDocument(basketTo.getdocument());

        doc = doc.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
        doc = doc.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "");
        doc = doc.trim();
        JSONObject object = XML.toJSONObject(doc);
        doc = object.toString(4);
        BasketsInfoTO basketsInfoTO = new BasketsInfoTO(bId, manageBasketTO.getBTypeID(), manageBasketTO.getName(), doc);
        basketsToc.add(basketsInfoTO);
        }
    basketInfoRestTO.setBasketsInfoTOList(basketsToc);
    ObjectMapper mapper = new ObjectMapper();
    responseXML = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(basketInfoRestTO);
    responseXML = responseXML.replace("\\\"", "\"");
    responseXML = responseXML.replace("\\n", "");
}

任何帮助都是非常感谢的。谢谢

h7appiyu

h7appiyu1#

解析和替换XML / JSON字符串值中的任何内容并不是一个好的解决方案。您可能可以使用引号解决上述问题,但您的代码可读性较差,并且容易出错-将来可能会出现一些新的错误情况,但您的代码将无法处理这些错误,除非重新重构以前编写的代码(SOLID中的O失败)。这可能会有所帮助。尽可能地在代码中分离责任(单一责任). org.JSON库(您在代码中使用的)处理所有XML标准,以便将有效的XML转换为JSONObject,而不会出现任何问题:
对于双引号的情况,可能是您的XML输入无效,或者您的Utilities.getStringFromDocument方法违反了XML规范规则。如我的代码所示,转换XML字符串-前后文档不会违反XML / JSON标准中的任何规范;如果输入的XML字符串包含双引号,那么转换后的JSON字符串也可以。如果输入的XML字符串包含双引号,并且您希望在转换过程中删除它们,那么您可以先转换整个文档,然后通过分别从文本创建JSONObject / JSONArray示例来重新构造data

public static void main(String[] args) {
        StringBuilder xmlText = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                .append("<sample>")
                .append("<rec1>John</rec1>")
                .append("<rec2>Snow</rec2>")
                .append("<data>")
                .append("<a>Season 1</a>")
                .append("<b>Episode 1</b>")
                .append("</data>")
                .append("</sample>");

        // below two lines of code were added in order to show no quote issue might occur in Document conversion case - like question has
        Document doc = convertStringToDocument(xmlText.toString());
        System.out.println("XML string: " + convertDocumentToString(doc));

        JSONObject xmlJSONObj = XML.toJSONObject(xmlText.toString());
        System.out.println("JSON string: " + xmlJSONObj.toString());
    }

    private static Document convertStringToDocument(String input) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new InputSource(new StringReader(input)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String convertDocumentToString(Document document) {
        TransformerFactory tf = TransformerFactory.newInstance();

        try {
            Transformer transformer = tf.newTransformer();
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // remove XML declaration
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));
            return writer.getBuffer().toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }
g6ll5ycj

g6ll5ycj2#

您可以将双引号替换为:

String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);

相关问题