我应该如何从JSON中转义字符串?

时间:2020-12-04 22:25:53

When creating JSON data manually, how should I escape string fields? Should I use something like Apache Commons Lang's StringEscapeUtilities.escapeHtml, StringEscapeUtilities.escapeXml, or should I use java.net.URLEncoder?

在手动创建JSON数据时,我应该如何退出字符串字段?我应该使用类似于Apache Commons Lang的stringescapeuti诉讼。escapehtml, stringescapeuti诉讼。escapexml,或者我应该使用java.net.URLEncoder吗?

The problem is that when I use SEU.escapeHtml, it doesn't escape quotes and when I wrap the whole string in a pair of 's, a malformed JSON will be generated.

问题是,当我使用SEU.escapeHtml时,它不会转义引号,当我用一对's包装整个字符串时,会生成一个格式不正确的JSON。

17 个解决方案

#1


133  

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

理想情况下,在您的语言中找到一个JSON库,您可以将适当的数据结构提供给它,并让它为如何避免问题而烦恼。它会让你更清醒。如果由于某种原因你没有一个图书馆在你的语言,你不想使用一个(我不建议这个¹),或您正在编写一个JSON库,请继续阅读。

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

根据RFC来逃离它。JSON是相当*的:您必须摆脱的唯一字符是\,“和控制代码(任何小于U+0020的字符)。

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

这种转义的结构是特定于JSON的。您需要一个特定于JSON的函数。所有的逃脱可以写成\ uXXXX XXXX是utf - 16编码单元¹字符。有一些快捷方式,例如\\,也可以工作。(它们的输出更小、更清晰。)

For full details, see the RFC.

有关详细信息,请参见RFC。

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

JSON的转义是基于JS构建的,所以它使用\uXXXX,其中XXXX是一个UTF-16代码单元。对于BMP之外的代码点,这意味着编码代理对,这会变得有点麻烦。(或者,您可以直接输出字符,因为JSON编码为Unicode文本,并允许这些特殊字符。)

#2


48  

Extract From Jettison:

从抛弃提取:

 public static String quote(String string) {
         if (string == null || string.length() == 0) {
             return "\"\"";
         }

         char         c = 0;
         int          i;
         int          len = string.length();
         StringBuilder sb = new StringBuilder(len + 4);
         String       t;

         sb.append('"');
         for (i = 0; i < len; i += 1) {
             c = string.charAt(i);
             switch (c) {
             case '\\':
             case '"':
                 sb.append('\\');
                 sb.append(c);
                 break;
             case '/':
 //                if (b == '<') {
                     sb.append('\\');
 //                }
                 sb.append(c);
                 break;
             case '\b':
                 sb.append("\\b");
                 break;
             case '\t':
                 sb.append("\\t");
                 break;
             case '\n':
                 sb.append("\\n");
                 break;
             case '\f':
                 sb.append("\\f");
                 break;
             case '\r':
                sb.append("\\r");
                break;
             default:
                 if (c < ' ') {
                     t = "000" + Integer.toHexString(c);
                     sb.append("\\u" + t.substring(t.length() - 4));
                 } else {
                     sb.append(c);
                 }
             }
         }
         sb.append('"');
         return sb.toString();
     }

#3


32  

Try this org.codehaus.jettison.json.JSONObject.quote("your string").

试试这个org.codehaus.jettison.json.JSONObject。字符串引号(“你”)。

Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

在这里下载:http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

#4


22  

org.json.simple.JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.

escape(): escape()逃离引号,\,\,\,\,\ \ \ \ \ \ \ \ \ \ \和其他控制字符。它可以用来逃避JavaScript代码。

import org.json.simple.JSONObject;
String test =  JSONObject.escape("your string");

#5


19  

Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+

Apache commons lang现在支持这一点。只要确保您的类路径上有一个最新版本的Apache commons lang。你需要3.2以上的版本

Release Notes for version 3.2

版本3.2的发行说明。

LANG-797: Added escape/unescapeJson to StringEscapeUtils.

朗-797:增加了逃跑/逃脱的机会。

#6


8  

org.json.JSONObject quote(String data) method does the job

org.json。JSONObject引用(字符串数据)方法完成任务。

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

从文档中提取:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

将数据编码为JSON字符串。这将应用引号和任何必要的字符转义。[…]Null将被解释为空字符串。

#7


6  

StringEscapeUtils.escapeJavaScript / StringEscapeUtils.escapeEcmaScript should do the trick too.

逃避现实,逃避现实。逃避现实的人也应该玩这个把戏。

#8


3  

Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.

不确定您所说的“手动创建json”是什么意思,但是您可以使用gson (http://code.google.com/p/google-gson/)之类的东西,并将您的HashMap、数组、字符串等转换为json值。我建议使用一个框架。

#9


3  

Use EscapeUtils class in commons lang API.

在commons lang API中使用EscapeUtils类。

EscapeUtils.escapeJavaScript("Your JSON string");

#10


2  

I have not spent the time to make 100% certain, but it worked for my inputs enough to be accepted by online JSON validators:

我没有花时间百分之百地确定,但它为我的输入工作,足以让在线JSON验证器接受:

org.apache.velocity.tools.generic.EscapeTool.EscapeTool().java("input")

although it does not look any better than org.codehaus.jettison.json.JSONObject.quote("your string")

尽管它看起来并不比org.codehaus.jettison.json.JSONObject更好。引号(“字符串”)

I simply use velocity tools in my project already - my "manual JSON" building was within a velocity template

我只是在我的项目中使用velocity工具——我的“手动JSON”构建在velocity模板中。

#11


2  

For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:

对于那些来这里寻找命令行解决方案的人,比如我,cURL的——data-urlencode可以正常工作:

curl -G -v -s --data-urlencode 'query={"type" : "/music/artist"}' 'https://www.googleapis.com/freebase/v1/mqlread'

sends

发送

GET /freebase/v1/mqlread?query=%7B%22type%22%20%3A%20%22%2Fmusic%2Fartist%22%7D HTTP/1.1

, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if

为例。更大的JSON数据可以放在一个文件中,并且您可以使用@语法指定要在将要转义的数据中发出的文件。例如,如果

$ cat 1.json 
{
  "type": "/music/artist",
  "name": "The Police",
  "album": []
}

you'd use

你会使用

curl -G -v -s --data-urlencode query@1.json 'https://www.googleapis.com/freebase/v1/mqlread'

And now, this is also a tutorial on how to query Freebase from the command line :-)

现在,这也是一个关于如何从命令行查询Freebase的教程:-)

#12


2  

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

如果您使用fastexml jackson,您可以使用以下方法:com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(输入)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

如果您使用codehaus jackson,您可以使用以下功能:org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(输入)

#13


1  

Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.

考虑苎麻JsonWriter类。它有一个很好的API,它可以减少复制到最小值,所有的东西都可以很好地流到一个文件,OutputStream等等。

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.buffer(Okio.sink(os)));
json.beginObject();
json.name("id").value(getId());
json.name("scores");
json.beginArray();
for (Double score : getScores()) {
  json.value(score);
}
json.endArray();
json.endObject();

If you want the string in hand:

如果你想要手上的绳子:

Buffer b = new Buffer(); // okio.Buffer
JsonWriter writer = new JsonWriter(b);
//...
String jsonString = b.readUtf8();

#14


0  

If you need to escape JSON inside JSON string, use org.json.JSONObject.quote("your json string that needs to be escaped") seem to work well

如果需要在JSON字符串中转义JSON,请使用org.json.JSONObject。引用(“需要转义的json字符串”)似乎运行良好。

#15


0  

using the \uXXXX syntax can solve this problem, google UTF-16 with the name of the sign, you can find out XXXX, for example:utf-16 double quote

使用\uXXXX语法可以解决这个问题,使用符号的名称谷歌UTF-16,您可以找到XXXX,例如:UTF-16双引号。

#16


0  

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

显示实际实现的方法都是错误的。我没有Java代码,只是为了记录,你可以很容易地转换这个c# -代码:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

由mono-project @ https://github.com/mono/mono/blob/master/mcs/class/system.web/httputility.cs提供。

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

这可以被压缩成。

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

#17


0  

I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.

我认为2017年最好的答案是使用javax。json api。使用javax.json。JsonBuilderFactory创建json对象,然后使用javax.json.JsonWriterFactory将对象写出来。很好的构建器/作家组合。

#1


133  

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

理想情况下,在您的语言中找到一个JSON库,您可以将适当的数据结构提供给它,并让它为如何避免问题而烦恼。它会让你更清醒。如果由于某种原因你没有一个图书馆在你的语言,你不想使用一个(我不建议这个¹),或您正在编写一个JSON库,请继续阅读。

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

根据RFC来逃离它。JSON是相当*的:您必须摆脱的唯一字符是\,“和控制代码(任何小于U+0020的字符)。

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

这种转义的结构是特定于JSON的。您需要一个特定于JSON的函数。所有的逃脱可以写成\ uXXXX XXXX是utf - 16编码单元¹字符。有一些快捷方式,例如\\,也可以工作。(它们的输出更小、更清晰。)

For full details, see the RFC.

有关详细信息,请参见RFC。

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

JSON的转义是基于JS构建的,所以它使用\uXXXX,其中XXXX是一个UTF-16代码单元。对于BMP之外的代码点,这意味着编码代理对,这会变得有点麻烦。(或者,您可以直接输出字符,因为JSON编码为Unicode文本,并允许这些特殊字符。)

#2


48  

Extract From Jettison:

从抛弃提取:

 public static String quote(String string) {
         if (string == null || string.length() == 0) {
             return "\"\"";
         }

         char         c = 0;
         int          i;
         int          len = string.length();
         StringBuilder sb = new StringBuilder(len + 4);
         String       t;

         sb.append('"');
         for (i = 0; i < len; i += 1) {
             c = string.charAt(i);
             switch (c) {
             case '\\':
             case '"':
                 sb.append('\\');
                 sb.append(c);
                 break;
             case '/':
 //                if (b == '<') {
                     sb.append('\\');
 //                }
                 sb.append(c);
                 break;
             case '\b':
                 sb.append("\\b");
                 break;
             case '\t':
                 sb.append("\\t");
                 break;
             case '\n':
                 sb.append("\\n");
                 break;
             case '\f':
                 sb.append("\\f");
                 break;
             case '\r':
                sb.append("\\r");
                break;
             default:
                 if (c < ' ') {
                     t = "000" + Integer.toHexString(c);
                     sb.append("\\u" + t.substring(t.length() - 4));
                 } else {
                     sb.append(c);
                 }
             }
         }
         sb.append('"');
         return sb.toString();
     }

#3


32  

Try this org.codehaus.jettison.json.JSONObject.quote("your string").

试试这个org.codehaus.jettison.json.JSONObject。字符串引号(“你”)。

Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

在这里下载:http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

#4


22  

org.json.simple.JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.

escape(): escape()逃离引号,\,\,\,\,\ \ \ \ \ \ \ \ \ \ \和其他控制字符。它可以用来逃避JavaScript代码。

import org.json.simple.JSONObject;
String test =  JSONObject.escape("your string");

#5


19  

Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+

Apache commons lang现在支持这一点。只要确保您的类路径上有一个最新版本的Apache commons lang。你需要3.2以上的版本

Release Notes for version 3.2

版本3.2的发行说明。

LANG-797: Added escape/unescapeJson to StringEscapeUtils.

朗-797:增加了逃跑/逃脱的机会。

#6


8  

org.json.JSONObject quote(String data) method does the job

org.json。JSONObject引用(字符串数据)方法完成任务。

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

从文档中提取:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

将数据编码为JSON字符串。这将应用引号和任何必要的字符转义。[…]Null将被解释为空字符串。

#7


6  

StringEscapeUtils.escapeJavaScript / StringEscapeUtils.escapeEcmaScript should do the trick too.

逃避现实,逃避现实。逃避现实的人也应该玩这个把戏。

#8


3  

Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.

不确定您所说的“手动创建json”是什么意思,但是您可以使用gson (http://code.google.com/p/google-gson/)之类的东西,并将您的HashMap、数组、字符串等转换为json值。我建议使用一个框架。

#9


3  

Use EscapeUtils class in commons lang API.

在commons lang API中使用EscapeUtils类。

EscapeUtils.escapeJavaScript("Your JSON string");

#10


2  

I have not spent the time to make 100% certain, but it worked for my inputs enough to be accepted by online JSON validators:

我没有花时间百分之百地确定,但它为我的输入工作,足以让在线JSON验证器接受:

org.apache.velocity.tools.generic.EscapeTool.EscapeTool().java("input")

although it does not look any better than org.codehaus.jettison.json.JSONObject.quote("your string")

尽管它看起来并不比org.codehaus.jettison.json.JSONObject更好。引号(“字符串”)

I simply use velocity tools in my project already - my "manual JSON" building was within a velocity template

我只是在我的项目中使用velocity工具——我的“手动JSON”构建在velocity模板中。

#11


2  

For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:

对于那些来这里寻找命令行解决方案的人,比如我,cURL的——data-urlencode可以正常工作:

curl -G -v -s --data-urlencode 'query={"type" : "/music/artist"}' 'https://www.googleapis.com/freebase/v1/mqlread'

sends

发送

GET /freebase/v1/mqlread?query=%7B%22type%22%20%3A%20%22%2Fmusic%2Fartist%22%7D HTTP/1.1

, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if

为例。更大的JSON数据可以放在一个文件中,并且您可以使用@语法指定要在将要转义的数据中发出的文件。例如,如果

$ cat 1.json 
{
  "type": "/music/artist",
  "name": "The Police",
  "album": []
}

you'd use

你会使用

curl -G -v -s --data-urlencode query@1.json 'https://www.googleapis.com/freebase/v1/mqlread'

And now, this is also a tutorial on how to query Freebase from the command line :-)

现在,这也是一个关于如何从命令行查询Freebase的教程:-)

#12


2  

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

如果您使用fastexml jackson,您可以使用以下方法:com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(输入)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

如果您使用codehaus jackson,您可以使用以下功能:org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(输入)

#13


1  

Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.

考虑苎麻JsonWriter类。它有一个很好的API,它可以减少复制到最小值,所有的东西都可以很好地流到一个文件,OutputStream等等。

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.buffer(Okio.sink(os)));
json.beginObject();
json.name("id").value(getId());
json.name("scores");
json.beginArray();
for (Double score : getScores()) {
  json.value(score);
}
json.endArray();
json.endObject();

If you want the string in hand:

如果你想要手上的绳子:

Buffer b = new Buffer(); // okio.Buffer
JsonWriter writer = new JsonWriter(b);
//...
String jsonString = b.readUtf8();

#14


0  

If you need to escape JSON inside JSON string, use org.json.JSONObject.quote("your json string that needs to be escaped") seem to work well

如果需要在JSON字符串中转义JSON,请使用org.json.JSONObject。引用(“需要转义的json字符串”)似乎运行良好。

#15


0  

using the \uXXXX syntax can solve this problem, google UTF-16 with the name of the sign, you can find out XXXX, for example:utf-16 double quote

使用\uXXXX语法可以解决这个问题,使用符号的名称谷歌UTF-16,您可以找到XXXX,例如:UTF-16双引号。

#16


0  

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

显示实际实现的方法都是错误的。我没有Java代码,只是为了记录,你可以很容易地转换这个c# -代码:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

由mono-project @ https://github.com/mono/mono/blob/master/mcs/class/system.web/httputility.cs提供。

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

这可以被压缩成。

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

#17


0  

I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.

我认为2017年最好的答案是使用javax。json api。使用javax.json。JsonBuilderFactory创建json对象,然后使用javax.json.JsonWriterFactory将对象写出来。很好的构建器/作家组合。