Skip to main content

Produce a string in double quotes with backslash sequences in all the right places.

using System;
using System.Globalization;
using System.Text;

namespace Ext.Net.Utilities
{
    /// <summary>
    /// </summary>
    public static class JsonUtils
    {
        /// <summary>
        /// Produce a string in double quotes with backslash sequences in all the right places.
        /// </summary>
        /// <param name="s">A String</param>
        /// <returns>A String correctly formatted for insertion in a JSON message.</returns>
        public static string Enquote(string s)
        {
            if (s == null || s.Length == 0)
            {
                return "\"\"";
            }
            int length = s.Length;
            StringBuilder stringBuilder = new StringBuilder(length + 4);
            stringBuilder.Append('\"');
            for (int i = 0; i < length; i++)
            {
                char chr = s[i];
                if (chr == '\\' || chr == '\"' || chr == '>')
                {
                    stringBuilder.Append('\\');
                    stringBuilder.Append(chr);
                }
                else if (chr == '\b')
                {
                    stringBuilder.Append("\\b");
                }
                else if (chr == '\t')
                {
                    stringBuilder.Append("\\t");
                }
                else if (chr == '\n')
                {
                    stringBuilder.Append("\\n");
                }
                else if (chr == '\f')
                {
                    stringBuilder.Append("\\f");
                }
                else if (chr == '\r')
                {
                    stringBuilder.Append("\\r");
                }
                else if (chr >= ' ')
                {
                    stringBuilder.Append(chr);
                }
                else
                {
                    string str = new string(chr, 1);
                    string str1 = string.Concat("000", int.Parse(str, NumberStyles.HexNumber));
                    stringBuilder.Append(string.Concat("\\u", str1.Substring(str1.Length - 4)));
                }
            }
            stringBuilder.Append('\"');
            return stringBuilder.ToString();
        }
    }
}