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

时间:2017-02-02 07:22:23

标签: java json web-services double-quotes

我在JSON响应中获得了以下'数据'字段的双引号,如下所示 -

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

非常感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:0)

您可以将双引号替换为:

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

答案 1 :(得分:0)

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

P.S对于双引号的情况,可能您的XML输入无效或您的Utilities.getStringFromDocument方法违反了XML规范规则。正如我的代码转换XML字符串所示 - Document back和front并没有破坏XML / JSON标准中的任何规范;如果你的输入XML字符串包含双引号,那么转换后的JSON也可以。如果您的输入XML有双引号并且您想在转换期间删除它们,那么您可能首先转换整个文档,然后仅通过单独从文本创建JSONObject / JSONArray实例来重构数据

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