From e930269138e2142baa68e2bdd2075e6bd851e095 Mon Sep 17 00:00:00 2001 From: karma Date: Thu, 3 Dec 2026 10:44:43 +0700 Subject: [PATCH] Escape embedded quotes in CDL quoted values instead of dropping them --- src/main/java/org/json/CDL.java | 10 +++++++--- src/test/java/org/json/junit/CDLTest.java | 17 +++++++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/json/CDL.java b/src/main/java/org/json/CDL.java index 0e8046798..430284ea9 100644 --- a/src/main/java/org/json/CDL.java +++ b/src/main/java/org/json/CDL.java @@ -230,8 +230,9 @@ private static boolean shouldQuoteValue(String value, char delimiter) { } /** - * Append a row value surrounded by quotes, omitting characters that should - * not appear inside the quoted value. + * Append a row value surrounded by quotes, doubling embedded quotes and + * omitting control characters that should not appear inside the quoted + * value. * * @param sb the destination buffer * @param value the value to append @@ -241,7 +242,10 @@ private static void appendQuotedValue(StringBuilder sb, String value) { int length = value.length(); for (int j = 0; j < length; j += 1) { char c = value.charAt(j); - if (c >= ' ' && c != '"') { + if (c == '"') { + // escape an embedded quote by doubling it, as the parser expects + sb.append("\"\""); + } else if (c >= ' ') { sb.append(c); } } diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index e5eb9eda8..74a5c7984 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -387,6 +387,19 @@ public void textToJSONArrayAndBackToStringCustomDelimiter() { JSONArray expectedJsonArray = new JSONArray(EXPECTED_LINES); Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } - -} \ No newline at end of file + /** + * Embedded quotes must survive a CDL.toString round trip. + */ + @Test + public void embeddedQuotesRoundTrip() { + JSONArray jsonArray = new JSONArray(); + jsonArray.put(new JSONObject().put("a", "say \"hi\", ok").put("b", "\"start")); + String cdl = CDL.toString(jsonArray); + assertEquals("a,b\n\"say \"\"hi\"\", ok\",\"\"\"start\"\n", cdl); + JSONArray parsed = CDL.toJSONArray(cdl); + assertEquals("say \"hi\", ok", parsed.getJSONObject(0).getString("a")); + assertEquals("\"start", parsed.getJSONObject(0).getString("b")); + } + +}