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 = ?? 
2
  • Just use Json.NET, you can serialise and deserialise to and from any type you care to create. Commented Jul 30, 2013 at 14:52
  • possible duplicate of Json Deserialize C# Commented Jul 15, 2014 at 12:16

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Use jsonutils.com to generate the Type for you if your json structure is a bit more complex.
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; }
    }

2 Comments

Might it be worth constructing one DataContractJsonSerializer object (per serialisable type) instead of constructing a new one for each serialisation?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.