Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting \u0040 to @ in C#

The Facebook graph API's return to me the user's email address as

foo\u0040bar.com.

in a JSON object. I need to convert it to

[email protected].

There must be a built in method in .NET that changes the Unicode character expression (\u1234) to the actual unicode symbol.

Do you know what it is?

Note: I prefer not to use JSON.NET or JavaScriptSerializer for performance issues.

I think the problem is in my StreamReader:

        requestUrl = "https://graph.facebook.com/me?access_token=" + accessToken;
        request = WebRequest.Create(requestUrl) as HttpWebRequest;
        try
        {
            using (HttpWebResponse response2 = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                reader = new StreamReader(response2.GetResponseStream(),System.Text.Encoding.UTF8);
                string json = reader.ReadToEnd();

I tried different encodings for the StreamReader, UTF8, UTF7, Unicode, ... none worked.

Many thanks!

Thanks to L.B for correcting me. The problem was not in the StreamReader.

like image 706
Barka Avatar asked Nov 30 '11 18:11

Barka


1 Answers

Yes, there is some built in method for that, but that would involve something like using a compiler to parse the string as code...

Use a simple replace:

s = s.Replace(@"\u0040", "@");

For a more flexible solution, you can use a regular expression that can handle any unicode character:

s = Regex.Replace(s, @"\\u([\dA-Fa-f]{4})", v => ((char)Convert.ToInt32(v.Groups[1].Value, 16)).ToString());
like image 84
Guffa Avatar answered Sep 19 '22 01:09

Guffa