How to decode a JSON string using C#?

回眸只為那壹抹淺笑 提交于 2019-11-27 04:34:15

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

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; }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!