Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode a JSON string using C#?

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 = ?? 
like image 490
The Mask Avatar asked Oct 08 '11 21:10

The Mask


2 Answers

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
like image 149
Kakashi Avatar answered Nov 02 '22 23:11

Kakashi


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; }
    }
like image 30
The Muffin Man Avatar answered Nov 02 '22 22:11

The Muffin Man