Help deserializing my JSON

May 1, 2011 at 7:47 PM
Edited May 1, 2011 at 7:48 PM

Hi guys, it's first time to use JSON.NET and even use JSON in my desktop applications so can you please guide me?

I have a website, created in drupal, and 1 module installed is the drupalchat module which throws JSON when polling.

here's the sample

 

{
   "messages":[
      {
         "message":"hilo",
         "timestamp":"23:55",
         "uid1":"7",
         "name":"shiftypowers"
      }
   ],
   "total_messages":"1",
   "last_timestamp":"1304265309",
   "buddylist":{
      "476":{
         "name":"Gandang_hari",
         "status":"1"
      },
      "506":{
         "name":"ichigo",
         "status":"1"
      },
      "186":{
         "name":"Jinn",
         "status":"1"
      },
      "7":{
         "name":"shiftypowers",
         "status":"1"
      },
      "total":4
   }
}

 

if you noticed the numbers 476, 506, 186, and 7 - those were user ids, and there will be thousands of them soon.

My concern is, how do you get the user ids and the name and status?

I have a code here:

 

namespace ElakoChat
{
    public class ElakoChatPollData
    {
        public ElakoChatPollData()
        {
            messages = new List<messages>();
        }
        public List<messages> messages { get; set; }
        public string total_messages { get; set; }
        public string last_timestamp { get; set; }
        public buddylist buddylist { get; set; }
    }

    public class messages
    {
        public string message { get; set; }
        public string timestamp { get; set; }
        public string uid1 { get; set; }
        public string name { get; set; }
    }

    public class buddylist
    {
        // what should I put here ??
        //public List<userinfo> uid { get; set; } // i don't think this is correct
        public Dictionary<int, userinfo> Users { get; set; }
        public string total { get; set; }
    }

    public class userinfo
    {
        public string name { get; set; }
        public string status { get; set; }
    }
}

 

and the way I use this is

ElakoChatPollData epd2 = Newtonsoft.Json.JsonConvert.DeserializeObject<ElakoChatPollData>(chatpoll);
Console.WriteLine("total online: " + epd.buddylist.total);
Console.WriteLine("online users: " + epd.buddylist.Users[0].name); // just get the 1st online user
// but unfortunately, am having an error "Object reference not set to an instance of an object." here "epd.buddylist.Users"

 

kindly please help and guide me retrieving the buddylist please?

May 2, 2011 at 7:33 AM

please help