Convert \ u0040 to @ in C #

Facebook graphical API returns me the user's email address as

foo\u0040bar.com .

in the JSON object. I need to convert it to

foo@bar.com .

.NET should have a built-in method that changes the Unicode character expression (\ u1234) to the actual Unicode character.

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 StreamReader, UTF8, UTF7, Unicode, ... did not work.

Thank you very much!

Thanks LB for correcting me. The problem is not in StreamReader.

+4
source share
2 answers

Json responses are not binary data to convert to string using some encodings. Instead, they are correctly decoded by your browser or HttpWebResponse , as in your example. You need to do the second processing (regular expression, deserializers, etc.) to get the final data.

See what you get webClient.DownloadString("https://graph.facebook.com/HavelVaclav?access_token=????") without any encoding

 {"id":"100000042150992", "name":"Havel V\u00e1clav", "first_name":"Havel", "last_name":"V\u00e1clav", "link":"http:\/\/www.facebook.com\/havel.vaclav", "username":"havel.vaclav", "gender":"male", "locale":"cs_CZ" } 

Will your encoding change \/ to / ?

So the problem is not with your StreamReader .

+2
source

Yes, there is some kind of built-in method for this, but it will require something like using a compiler to parse a string as code ...

Use a simple replacement:

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

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

 s = Regex.Replace(s, @"\\u([\dA-Fa-f]{4})", v => ((char)Convert.ToInt32(v.Groups[1].Value, 16)).ToString()); 
+10
source

Source: https://habr.com/ru/post/1383948/


All Articles