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