How to avoid JSON string?

Are there any classes / functions that can be used to simply speed up JSON? I would rather not write my own.

+64
json c # escaping
Aug 06 '09 at 23:40
source share
12 answers

You can check out Introduction to JSON in .Net on MSDN and the JsonConvert class from JayRock JSON .

As a note, we use Jayrock for all our Json purposes for our products.

+8
Aug 6 '09 at 23:50
source share

Based on the response from Dejan , what you can do is import the System.Web.Helpers .NET Framework assembly , then use the following function:

 static string EscapeForJson(string s) { string quoted = System.Web.Helpers.Json.Encode(s); return quoted.Substring(1, quoted.Length - 2); } 

Substring required because Encode automatically surrounds double- Substring strings.

+36
Jan 30 '14 at 11:40
source share

I am using System.Web.HttpUtility.JavaScriptStringEncode

 string quoted = HttpUtility.JavaScriptStringEncode(input); 
+36
Jun 15 '16 at 19:04
source share

For those who use the very popular Json.Net project from Newtonsoft, the task is trivial:

 using Newtonsoft.Json; .... var s = JsonConvert.ToString(@"a\b"); Console.WriteLine(s); .... 

This code prints:

"A \\ b"

That is, the resulting string value contains quotation marks as well as escaped backslash.

+22
01 Oct '14 at 23:01
source share

Yes, just add the following function to your Utils class:

  public static string cleanForJSON(string s) { if (s == null || s.Length == 0) { return ""; } char c = '\0'; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); String t; for (i = 0; i < len; i += 1) { c = s[i]; switch (c) { case '\\': case '"': sb.Append('\\'); sb.Append(c); break; case '/': 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" + String.Format("X", c); sb.Append("\\u" + t.Substring(t.Length - 4)); } else { sb.Append(c); } break; } } return sb.ToString(); } 
+20
Jul 17 '13 at 5:14
source share

I used the following code to avoid the string value for json. You need to add your `` '' to the output of the following code:

 public static string EscapeStringValue(string value) { const char BACK_SLASH = '\\'; const char SLASH = '/'; const char DBL_QUOTE = '"'; var output = new StringBuilder(value.Length); foreach (char c in value) { switch (c) { case SLASH: output.AppendFormat("{0}{1}", BACK_SLASH, SLASH); break; case BACK_SLASH: output.AppendFormat("{0}{0}", BACK_SLASH); break; case DBL_QUOTE: output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE); break; default: output.Append(c); break; } } return output.ToString(); } 
+18
Aug 07 '13 at
source share

I would also recommend using the JSON.NET library, but if you need to avoid Unicode characters (for example, the format \ uXXXX) as a result, you get a JSON string, you may have to do it yourself. See Converting Unicode strings to ascii escape string for an example.

+4
Nov 18 '09 at 15:59
source share

I ran speed tests on some of these answers for a long line and a short line. The Clive Paterson code won a good bit, apparently because others consider serialization options. Here are my results:

 Apple Banana System.Web.HttpUtility.JavaScriptStringEncode: 140ms System.Web.Helpers.Json.Encode: 326ms Newtonsoft.Json.JsonConvert.ToString: 230ms Clive Paterson: 108ms \\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape System.Web.HttpUtility.JavaScriptStringEncode: 2849ms System.Web.Helpers.Json.Encode: 3300ms Newtonsoft.Json.JsonConvert.ToString: 2827ms Clive Paterson: 1173ms 

And here is the test code:

 public static void Main(string[] args) { var testStr1 = "Apple Banana"; var testStr2 = @"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape"; foreach (var testStr in new[] { testStr1, testStr2 }) { var results = new Dictionary<string,List<long>>(); for (var n = 0; n < 10; n++) { var count = 1000 * 1000; var sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr); } var t = sw.ElapsedMilliseconds; results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t); sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { var s = System.Web.Helpers.Json.Encode(testStr); } t = sw.ElapsedMilliseconds; results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t); sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { var s = Newtonsoft.Json.JsonConvert.ToString(testStr); } t = sw.ElapsedMilliseconds; results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t); sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { var s = cleanForJSON(testStr); } t = sw.ElapsedMilliseconds; results.GetOrCreate("Clive Paterson").Add(t); } Console.WriteLine(testStr); foreach (var result in results) { Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms"); } Console.WriteLine(); } Console.ReadLine(); } 
+4
Aug 11 '16 at 19:19
source share

The methods proposed here are erroneous.
Why take the risk so far when you can just use System.Web.HttpUtility.JavaScriptEncode?

If you are at a lower level, you can simply copy it from mono

Provided by monoproject @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/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(); } 

It can be compressed 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(); } } 
+4
Sep 16 '16 at 8:41
source share
+3
Jan 05 '14 at 16:16
source share
 String.Format("X", c); 

It just gives out: X

Try this instead:

 string t = ((int)c).ToString("X"); sb.Append("\\u" + t.PadLeft(4, '0')); 
+2
Dec 26 '13 at 21:05
source share

There is a Json library in Codeplex

0
Aug 6 '09 at 23:42
source share



All Articles