简体   繁体   English

如何在C#中将JSON反序列化为对象

[英]how to deserialize json into objects in c#

could not deserialize json into objects. 无法将json反序列化为对象。 try to use DataContractJsonSerializer . 尝试使用DataContractJsonSerializer
here is how i use it 这是我的用法
have NO idea how to cope with it.. 不知道该如何应对。
CLASS

    [Serializable]
    public class user
    {
        public user() { }
        public user(string _uid, string _first_name, string _last_name, string _online)
        {
            this._uid = _uid;
            this._first_name = _first_name;
            this._last_name = _last_name;
            this._online = _online;
        }

        string _uid;
        string _first_name;
        string _last_name;
        string _online;

        [DataMember]
        public string uid
        {
            get { return _uid; }
            set { _uid = value; }
        }

        [DataMember]
        public string first_name
        {
            get { return _first_name; }
            set { _first_name = value; }
        }

        [DataMember]
        public string last_name
        {
            get { return _last_name; }
            set { _last_name = value; }
        }
        [DataMember]
        public string online
        {
            get { return _online; }
            set { _online = value; }
        }
    } 

DataContractJsonSerializer Usage DataContractJsonSerializer的用法

        WebRequest w = WebRequest.Create(string.Format("https://api.vk.com/method/friends.get?uid=6631031&fields=uid,first_name,last_name&access_token={0}",_accesstoken));
        Stream stream = w.GetResponse().GetResponseStream();

        //StreamReader sread = new StreamReader(stream);//here i can get the result into a string
        //string sLine = sread.ReadLine();              //to make sure the result is valid json

        DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(user[]));
        var result = (user[]) json.ReadObject(stream);

EXAMPLE OF MY JSON 我的JSON示例

"{\"response\":[{\"uid\":779358,\"first_name\":\"Dark\",\"last_name\":\"Knight\",\"online\":0},{\"uid\":1023931,\"first_name\":\"Екатерина\",\"last_name\":\"Гаврилова\",\"online\":0},{\"uid\":2475856,\"first_name\":\"Даша\",\"last_name\":\"Матвеева\",\"online\":0},......]}"

You could define a wrapper object containing a response property of type user[] in order to reflect your JSON structure: 您可以定义一个包装对象,其中包含类型为user[]response属性,以反映您的JSON结构:

[DataContract]
public class Result
{
    [DataMember]
    public user[] response { get; set; }
}

and then: 接着:

DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Result));
Result result = (Result)json.ReadObject(stream);
user[] users = result.response;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM