How to decode a JSON string using C#?
Asked Answered
S

2

9

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 = ?? 
Strophanthus answered 8/10, 2011 at 21:45 Comment(2)
Just use Json.NET, you can serialise and deserialise to and from any type you care to create.Thousandfold
possible duplicate of Json Deserialize C#Guffey
N
12

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
Niela answered 9/10, 2011 at 2:32 Comment(2)
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.Dorita
Use jsonutils.com to generate the Type for you if your json structure is a bit more complex.Maturity
D
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; }
    }
Dorita answered 8/10, 2011 at 21:48 Comment(2)
Might it be worth constructing one DataContractJsonSerializer object (per serialisable type) instead of constructing a new one for each serialisation?Dorettadorette
@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.Ahmed

© 2022 - 2024 — McMap. All rights reserved.