String to JSON

Say you’ve loaded a text into a string and you’d like to convert all special characters such as accented ones ( á é ñ) to unicode escapes inside of the string so you can save it as a standard JSON string or file.

Example:

“Coca-Cola & Nestlé” to “Coca\u002DCola \u0026 Nestl\u00E9”

public static string ToJSON(string text)
{
    StringBuilder json= new StringBuilder(text.Length * 6);
    Byte[] bytes = Encoding.Unicode.GetBytes(text);

    foreach (var b in bytes)
    {
        if (b == 0)
            continue;

        if (b == 96)
        {
            json.Append('\'');
            continue;
        }

        if ((b > 64 && b < 126) || (b > 47 && b < 58))
        {
            json.Append((char)b);
            continue;
        }

        switch (b)
        {
            case 59:
            case 58:
            case 32:
            case 33:
            case 36:
            case 39:
            case 34:
            case 44:
            case 46:
                json.Append((char)b);
                break;
            default:
                json.AppendFormat(@"\u{0:X4}", b);
                break;
        }
    }

    return json.ToString();
}

//opposite function
public static string ToStringFromJSON(string json)
{
    Regex regex = new Regex(@"\\[uU]([0-9A-F]{4})", RegexOptions.IgnoreCase);
    return regex.Replace(json, match => ((char)int.Parse(match.Groups[1].Value,
        NumberStyles.HexNumber)).ToString());

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s