8

I'm looking for an example code/lib to decode a JSON string using C#.

To encode I can do this:

var data = new Dictionary<string,string>(); 
data.Add("..", "..."); 
var json_encoded = new JavaScriptSerializer().Serialize(data); 

but how do I decode?

var json_decoded = ?? 
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
The Mask
  • 17,007
  • 37
  • 111
  • 185
  • Just use [Json.NET](http://james.newtonking.com/projects/json-net.aspx), you can serialise and deserialise to and from any type you care to create. – Trevor Pilley Jul 30 '13 at 14:52
  • possible duplicate of [Json Deserialize C#](http://stackoverflow.com/questions/7895105/json-deserialize-c-sharp) – nawfal Jul 15 '14 at 12:16

2 Answers2

11

You can do this:

var data = new Dictionary<string, string>();
data.Add("foo", "baa"); 

JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded

var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
Kakashi
  • 2,165
  • 14
  • 19
  • 3
    It should be noted that this doesn't deserialize the JSON string back to a Type, which might be fine in certain instances. I find deserializing the string to a Type is a much more robust solution. – The Muffin Man Apr 19 '12 at 22:08
  • Use https://jsonutils.com to generate the Type for you if your json structure is a bit more complex. – Rory Dec 09 '18 at 05:59
9

This will take JSON and convert it to a strongly typed class of which you specify (T)

public static T Deserialize<T>(string json)
        {
            var obj = Activator.CreateInstance<T>();
            using(var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                var serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T) serializer.ReadObject(ms);
                return obj;
            }
        }

This will take a class and serialize it as JSON

    public static string Serialize<T>(T obj)
    {
        var serializer = new DataContractJsonSerializer(obj.GetType());
        using (var ms = new MemoryStream())
        {
            serializer.WriteObject(ms, obj);
            return Encoding.Default.GetString(ms.ToArray());
        }
    }

Note: In the first example you will need to have a backing class to specify what type T is. So if you told it that T is of type User you would need to have this specified somewhere:

public class User
    {
        public string Username { get; set; }
        public string Firstname { get; set; }
    }
The Muffin Man
  • 19,585
  • 30
  • 119
  • 191
  • 2
    Might it be worth constructing *one* `DataContractJsonSerializer` object (per serialisable type) instead of constructing a new one for each serialisation? – Timwi Oct 08 '11 at 22:17
  • @Timwi, It depends. It's going to cost you more memory to hold the instances, but it's going to be less economic speed wise if you don't. It really boils down to your specific situation. Ideally, you'd want to keep serializers that will be used often, and throw away ones that won't. – cwharris Oct 08 '11 at 23:51