JSON 对象中的转义字符串
Escape string in a JSON object
我们使用 Freemarker 将一个 JSON 转换为另一个。输入 JSON 是这样的:
{"k1": "a", "k2":"line1. \n line2"}
Post使用Freemarker模板,将JSON转换为:
{ \n\n "p1": "a", \n\n "p2": "line1. \n line2"}
这是我们用来进行转换的逻辑
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();
转换为 JSON 对象失败,因为键 k2 的字符串中有换行符,并出现以下异常:
Caused by: org.json.JSONException: Unterminated string at ...
我尝试使用以下但没有任何效果:
1. JSONObject.quote
2. JSONValue.escape
3. out.toString().replaceAll("[\n\r]+", "\\n");
由于开头的换行符,我得到以下异常:
Caused by: org.json.JSONException: Missing value at 1 [character 2 line 1]
有人能给我指出正确的方向吗?
编辑
在 OP 进一步澄清后,他的 freemarker 模板中有 "${key}": "${value}"
并且 ${value}
可能包含线路制动器。这种情况下的解决方案是使用${value?json_string}
.
我们使用 Freemarker 将一个 JSON 转换为另一个。输入 JSON 是这样的:
{"k1": "a", "k2":"line1. \n line2"}
Post使用Freemarker模板,将JSON转换为:
{ \n\n "p1": "a", \n\n "p2": "line1. \n line2"}
这是我们用来进行转换的逻辑
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();
转换为 JSON 对象失败,因为键 k2 的字符串中有换行符,并出现以下异常:
Caused by: org.json.JSONException: Unterminated string at ...
我尝试使用以下但没有任何效果:
1. JSONObject.quote
2. JSONValue.escape
3. out.toString().replaceAll("[\n\r]+", "\\n");
由于开头的换行符,我得到以下异常:
Caused by: org.json.JSONException: Missing value at 1 [character 2 line 1]
有人能给我指出正确的方向吗?
编辑
在 OP 进一步澄清后,他的 freemarker 模板中有 "${key}": "${value}"
并且 ${value}
可能包含线路制动器。这种情况下的解决方案是使用${value?json_string}
.