How to decode a JSON string using C#?

我们两清 提交于 2019-11-26 12:45:03

问题


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 = ?? 

回答1:


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



回答2:


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; }
    }


来源:https://stackoverflow.com/questions/7699972/how-to-decode-a-json-string-using-c

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