Question

could not deserialize json into objects. try to use 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

        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

"{\"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},......]}"
Was it helpful?

Solution

You could define a wrapper object containing a response property of type user[] in order to reflect your JSON structure:

[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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top