Convert Json Unicode to Utf8

12,246

As Tomalak pointed out, it can be done using the System.Web.Helpers.Json.Decode method (no external libraries, .NET Framework). You need to build a simple JSON object to fetch the decoded text:

// helper class
public class Dummy
{
    public String Field { get; set; }
}
//
var value = "V\u00E4xj\u00F6";
var sb = new StringBuilder();
sb.Append("{");
sb.Append(String.Format(@"""Field"" : ""{0}""", value));
sb.Append("}");
var dummy = Json.Decode(sb.ToString());
Console.WriteLine(dummy.Field);
// it works also without helper class
var obj = Json.Decode(sb.ToString());
Console.WriteLine(obj.Field);

The output is:

Växjö
Växjö

One possibility would be to use the Json.NET library to decode the string (or maybe for the whole JSON handling?). The deserializer decodes the string automatically. My test code looks like this:

// placeholder for the example
public class Sample
{
    public String Name { get; set; }
}
// 
var i = @"{ ""Name"" : ""V\u00E4xj\u00F6"" }";
var jsonConverter = Newtonsoft.Json.JsonConvert.DeserializeObject(i);
Console.WriteLine(jsonConverter.ToString());
//
var sample = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(i);
Console.WriteLine(sample.Name);

The output is:

{
  "Name": "Växjö"
}
Växjö
Share:
12,246
Emil
Author by

Emil

Updated on June 04, 2022

Comments

  • Emil
    Emil almost 2 years

    I'm facing a wierd problem when converting Json Unicode(?) to UTF8

    "V\u00E4xj\u00F6" should be "Växjö"

    Right now it seems like I've tried everything possible, but no luck.

    Any coding ninjas out there that may sit on a solution? I'm sure it's fairly easy but still can't seem to figure it out.

    Thank you

    • Tomalak
      Tomalak about 10 years
      Json.Decode should do what you want.
  • Emil
    Emil about 10 years
    Thank you for your answer. I'm not reading JSON-data, it's just one value that is formatted as json. If possible, I wish not to use any third library (such as Newtonsoft).
  • keenthinker
    keenthinker about 10 years
    I updated my answer - the code now relies only on the .NET Framework.