字符串json怎么把双引号去掉_如何删除双引号"从Json字符串

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

}

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

Error: Parse error on line 18:

... "document" : "[{"bc": { "b": {

-----------------------^

Expecting 'EOF', '}', ':', ',', ']'

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

解决方案

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:

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("")

.append("John")

.append("Snow")

.append("")

.append("Season 1")

.append("Episode 1")

.append("")

.append("");

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值