Search code examples
jsonescapingfreemarker

Escape string in a JSON object



We use Freemarker to transform one JSON to another. The input JSON is something like this:

{"k1": "a", "k2":"line1. \n line2"}

Post using the Freemarker template, the JSON is converted to:

{ \n\n "p1": "a", \n\n "p2": "line1. \n line2"}

Here is the logic we use to do the transformation

final Map<String, Object> input = JsonConverter.convertFromJson(input, Map.class);
final Template template = freeMarkerConfiguration.getTemplate("Template1.ftl");
final Writer out = new StringWriter();
template.process(input, out);
out.flush();
final String newlineFilteredResult = new JSONObject(out.toString).toString();

The conversion to JSON object fails due to a newline character inside a string for key k2 and gives the following exception:

Caused by: org.json.JSONException: Unterminated string at ...

I tried using the following but nothing works:
1. JSONObject.quote
2. JSONValue.escape
3. out.toString().replaceAll("[\n\r]+", "\\n");
I get the following exception due to the newline characters at the beginning as well:

Caused by: org.json.JSONException: Missing value at 1 [character 2 line 1]

Could someone please point me in the correct direction.


Solution

  • Edit

    After further clarification from OP he had "${key}": "${value}" in his freemarker template and ${value} could contain line brakes. The solution in this case is to use ${value?json_string}.