简体   繁体   English

如何动态转义Java中的JSON中的双引号

[英]How to escape double quotes in a JSON in Java dynamically

How to escape double quotes inside a JSON given the data in the JSON will be obtained dynamically in Java.给定 JSON 中的数据将在 Java 中动态获取,如何转义 JSON 中的双引号。

Example:例子:

{
    "key": "I ask silly questions on "https://www.stackoverflow.com". "
}

In this case, the value in the JSON is populated from dynamically let's say from a user input.在这种情况下,JSON 中的值是动态填充的,比方说来自用户输入。

I have tried StringEscapeUtils provided by apache-commons-lang ( https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html ), but this escapes the entire JSON where as the double quotes inside the JSON needs to escape again.我已经尝试过 apache-commons-lang ( https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html ) 提供的 StringEscapeUtils,但这逃脱了整个 JSON,其中 JSON 中的双引号需要再次转义。

Possible solution will be to use regex and filter out the value in JSON and escape once before escaping the overall JSON.可能的解决方案是使用正则表达式并过滤掉 JSON 中的值,并在 escaping 整体 JSON 之前转义一次。

But, is there any JAR to escape the inner contents of a JSON?但是,是否有任何 JAR 可以逃脱 JSON 的内部内容?

If doing json processing in java I would use Jackson databind and let it handle json generation.如果在 java 中进行 json 处理,我将使用Jackson 数据绑定并让它处理 json 代。 You will probably want to turn some knobs eventually, but simplest possible usage will probably do for this use case:您最终可能想要转动一些旋钮,但最简单的用法可能适用于此用例:

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(singletonMap("key", "I ask silly questions..."));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM