Recommended hosting
Jul 04 2005

C# encode a string for JSON JavaScript

Posted by admin under .NET

This function was found in this zipfile



  ///  FUNCTION Enquote Public Domain 2002 JSON.org
  ///  @author JSON.org
  ///  @version 0.1
  ///  Ported to C# by Are Bjolseth, teleplan.no
public static string Enquote(string s) 
{
	if (s == null || s.Length == 0) 
	{
		return "\"\"";
	}
	char         c;
	int          i;
	int          len = s.Length;
	StringBuilder sb = new StringBuilder(len + 4);
	string       t;

	sb.Append('"');
	for (i = 0; i < len; i += 1) 
	{
		c = s[i];
		if ((c == '\\') || (c == '"') || (c == '>'))
		{
			sb.Append('\\');
			sb.Append(c);
		}
		else if (c == '\b')
			sb.Append("\\b");
		else if (c == '\t')
			sb.Append("\\t");
		else if (c == '\n')
			sb.Append("\\n");
		else if (c == '\f')
			sb.Append("\\f");
		else if (c == '\r')
			sb.Append("\\r");
		else
		{
			if (c < ' ') 
			{
				//t = "000" + Integer.toHexString(c);
				string tmp = new string(c,1);
				t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber);
				sb.Append("\\u" + t.Substring(t.Length - 4));
			} 
			else 
			{
				sb.Append(c);
			}
		}
	}
	sb.Append('"');
	return sb.ToString();
}

It's public domain but the strange thing is that the zipfile is not linked from the json.org homepage, anyway my point is that the function - while it might not be rocket science, still is too good to have to just be lying inside a strange zipfile.

What does it do? In encodes a string so it can be used inside a JSON expression. It is so useful to be able to be alto to send anything (html, special characters etc) inside the json string.