Java转义JSON字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18898773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:06:12  来源:igfitidea点击:

Java escape JSON String?

javajsonnode.js

提问by Alosyius

I have the following JSON string that i am sending to a NodeJS server:

我有以下 JSON 字符串要发送到 NodeJS 服务器:

String string = "{\"id\":\"" + userID + "\",\"type\":\"" + methoden + "\",\"msg\":\"" + msget + "\", \"name\":\"" + namnet + "\", \"channel\":\"" + activeChatChannel + "\", \"visitorNick\":\"\", \"agentID\":\" " + agentID + "\"}";

PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "utf-8"));
pw.println(string);

The problem becomes when the string msgetcontains the character "and '

当字符串的问题变得msget包含字符"'

On the NodeJS server i am parsing the JSON like this:

在 NodeJS 服务器上,我像这样解析 JSON:

var obj = JSON.parse(message);

Any ideas how i can manage to send all characters without problems?

我有什么想法可以毫无问题地发送所有字符吗?

采纳答案by jabclab

I would use a library to create your JSON Stringfor you. Some options are:

我会使用一个库来String为你创建你的 JSON 。一些选项是:

This will make dealing with escaping much easier. An example (using org.json) would be:

这将使处理逃逸更容易。一个例子(使用org.json)是:

JSONObject obj = new JSONObject();

obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);

// etc.

final String json = obj.toString(); // <-- JSON string

回答by Silviu Burcea

Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

尝试在它们之前用 \ 替换所有 " 和 '。仅针对 msget 对象(我猜是字符串)执行此操作。不要忘记 \ 也必须转义。

回答by Sotirios Delimanolis

According to the answer here, quotes in values need to be escaped. You can do that with \"

根据这里的答案,需要对值中的引号进行转义。你可以这样做\"

So just repalce the quote in your values

所以只需重新引用你的价值观

msget = msget.replace("\"", "\\"");

回答by Dirk Lachowski

The best method would be using some JSON library, e.g. Hymanson ( http://Hymanson.codehaus.org).

最好的方法是使用一些 JSON 库,例如 Hymanson ( http://Hymanson.codehaus.org)。

But if this is not an option simply escape msget before adding it to your string:

但是,如果这不是一个选项,只需在将其添加到字符串之前转义 msget:

The wrong way to do this is

这样做的错误方法是

String msgetEscaped = msget.replaceAll("\"", "\\"");

Either use (as recommended in the comments)

要么使用(如评论中推荐的那样)

String msgetEscaped = msget.replace("\"", "\\"");

or

或者

String msgetEscaped = msget.replaceAll("\"", "\\\"");

A sample with all three variants can be found here: http://ideone.com/Nt1XzO

可以在此处找到包含所有三种变体的示例:http: //ideone.com/Nt1XzO

回答by Yeongjun Kim

org.json.simple.JSONObject.escape()escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

org.json.simple.JSONObject.escape()转义引号、、/、\r、\n、\b、\f、\t 和其他控制字符。

import org.json.simple.JSONValue;
JSONValue.escape("test string");

Add pom.xml when using maven

使用maven时添加pom.xml

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>

回答by orip

Consider Moshi's JsonWriterclass. It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.

考虑MoshiJsonWriter类。它有一个很棒的 AP​​I,它将复制减少到最低限度,一切都很好地流式传输到 OutputStream。

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.sink(os));
json
  .beginObject()
  .name("id").value(userID)
  .name("type").value(methodn)
  ...
  .endObject();

回答by rhengles

If you want to simply escape a string, not an object or array, use this:

如果您只想转义字符串,而不是对象或数组,请使用以下命令:

String escaped = JSONObject.valueToString(" Quotes \" ' ' \" ");

http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

回答by Ron DeSantis

The JSON specification at https://www.json.org/is very simple by design. Escaping characters in JSON strings is not hard. This code works for me:

https://www.json.org/ 上的 JSON 规范在设计上非常简单。转义 JSON 字符串中的字符并不难。这段代码对我有用:

private String escape(String raw) {
    String escaped = raw;
    escaped = escaped.replace("\", "\\");
    escaped = escaped.replace("\"", "\\"");
    escaped = escaped.replace("\b", "\b");
    escaped = escaped.replace("\f", "\f");
    escaped = escaped.replace("\n", "\n");
    escaped = escaped.replace("\r", "\r");
    escaped = escaped.replace("\t", "\t");
    // TODO: escape other non-printing characters using uXXXX notation
    return escaped;
}

回答by Sagar Jadhav

public static String ecapse(String jsString) {
    jsString = jsString.replace("\", "\\");
    jsString = jsString.replace("\"", "\\"");
    jsString = jsString.replace("\b", "\b");
    jsString = jsString.replace("\f", "\f");
    jsString = jsString.replace("\n", "\n");
    jsString = jsString.replace("\r", "\r");
    jsString = jsString.replace("\t", "\t");
    jsString = jsString.replace("/", "\/");
    return jsString;
}

回答by davnicwil

Apache Commons

阿帕奇公地

If you're already using Apache commons, it provides a static method for this:

如果您已经在使用 Apache commons,它会为此提供一个静态方法:

StringEscapeUtils.escapeJson("some string")

It converts any string into one that's properly escaped for inclusion in JSON

它将任何字符串转换为正确转义以包含在 JSON 中的字符串

See the documentation here

请参阅此处的文档