如何将json反序列化为c#中的对象

时间:2012-02-09 22:12:43

标签: c# json vk

无法将json反序列化为对象。尝试使用 DataContractJsonSerializer
这是我如何使用它不知道如何应对它。
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用法

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

我的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},......]}"

1 个答案:

答案 0 :(得分:0)

您可以定义一个包含response user[]类型属性的包装器对象,以反映您的JSON结构:

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

然后:

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