How to decode a JSON string using C#?

后端 未结 2 1591
旧时难觅i
旧时难觅i 2020-11-30 08:19

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(); 
d         


        
相关标签:
2条回答
  • 2020-11-30 08:58

    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
    
    0 讨论(0)
  • 2020-11-30 08:59

    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; }
        }
    
    0 讨论(0)
提交回复
热议问题