本文介绍了如何删除双引号"从Json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的JSON响应中的'data'字段下方得到双引号-

I'm getting double quotes for below 'data' field in JSON response like this -

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

在验证此JSOn时,出现以下验证错误

While validating this JSOn, I'm getting validation errors as below

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

我希望JSON响应显示为-

I want JSON response to be displayed as -

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

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

My server side code used is -

  {
    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", "");
}

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

Any help is much appreciated. Thanks

推荐答案

解析和替换XML / JSON字符串值中的任何内容都不是一个好的解决方案。您可能可以用引号解决上述问题,但是您的代码将不那么易读且容易出错-将来可能会出现一些新的错误情况,但是如果不重新重构先前编写的代码,您的代码将无法处理它们( O LID中的> O 失败)。我编写了一些次要的示例代码,可能会有所帮助。尝试将代码中的职责尽可能地分开(单一职责)。 org.JSON库(您在代码中使用的库)处理所有XML标准,以便有效的XML可以毫无问题地转换为JSONObject:

Parsing and replacing anything inside XML / JSON string values is not a good solution. You might be ok with solving above issue with quotes but your code will be less readable and error-prone - some new error cases might occur in future, but your code will not be able to handle them without refactoring previously written code again (O in SOLID fails). I've written minor sample code, which might help. Try to separate responsibilities in your code as much as you can (single responsibility). org.JSON library (which you used in your code) handles all XML standards so that valid XML will be converted to JSONObject without any issue:

PS对于双引号,可能是您的XML输入无效,或者您的 Utilities.getStringFromDocument 方法违反了XML规范规则。如我的转换XML字符串的代码所示-前后文档没有破坏XML / JSON标准中的任何规范;如果您输入的XML字符串包含双引号,那么转换后的JSON也会执行同样的操作。如果您输入的XML有双引号,并且您想在转换期间将其删除,那么您可能首先转换整个文档,然后仅通过分别从文本创建JSONObject / JSONArray实例来重构数据

P.S For double quote case, probably your XML input is not valid or your Utilities.getStringFromDocument method breaks XML specification rules. As shown in my code converting XML string - Document back and front doesn't break any specifications in XML / JSON standards; if your input XML string contains double quotes then converted JSON one will do as well. If your input XML has double quotes and you want to remove them during conversion, then you might first convert the whole document then re-struct data only by creating JSONObject / JSONArray instance from text separately.

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;
    }

这篇关于如何删除双引号&quot;从Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:11