Salman Mushtaq

Salman Mushtaq

  • NA
  • 284
  • 221.5k

Populate ComboBox from JSON Object

Dec 7 2017 3:28 AM
Hello, I have below Json
  1. [  
  2.     {  
  3.         "customerid": 1,  
  4.         "name": "ABS",  
  5.         "email": "true",  
  6.         "reference": "2016-03-21T10:44:32+03:00",  
  7.         "status": 0,  
  8.         "dateupdated": "2017-12-07T04:56:05.583"  
  9.     },  
  10.     {  
  11.         "customerid": 2,  
  12.         "name": "BMS",  
  13.         "email": "true",  
  14.         "reference": "2016-03-13T19:17:54+03:00",  
  15.         "status": 0,  
  16.         "dateupdated": "2017-12-07T04:56:05.757"  
  17.     },  
  18.     {  
  19.         "customerid": 3,  
  20.         "name": "XYA",  
  21.         "email": "true",  
  22.         "reference": "2016-03-13T19:17:54+03:00",  
  23.         "status": 0,  
  24.         "dateupdated": "2017-12-07T04:56:05.757"  
  25.     }  
  26. ]  
In my windows form I create class API.cs
  1. class API  
  2.     {  
  3.          
  4.     }  
  5.   
  6.     public class RootObject  
  7.     {  
  8.         public int customerid { getset; }  
  9.         public string name { getset; }  
  10.         public string email { getset; }  
  11.         public DateTime reference { getset; }  
  12.         public int status { getset; }  
  13.         public DateTime dateupdated { getset; }  
  14.     }  
I need to populate combo box customer_cb with "name".  I use DataContractJsonSerializer 
  1. WebClient client = new WebClient();  
  2.   string json = client.DownloadString(url);  
  3. using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))  
  4.                 {  
  5.                     DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(RootObject));  
  6.                     RootObject obj = (RootObject)deserializer.ReadObject(ms);  
  7.                       
  8.                     // Assign data to combo box  
  9.                     foreach(var name in obj.name)  
  10.                     {  
  11.                         ComboboxItem item = new ComboboxItem();  
  12.                         item.Text = name.ToString();  
  13.                         customer_cb.Items.Add(item);  
  14.                     }  
  15.                 }  
When I run the application I get error
  1. Object Reference not set to an instance of an object  
Please help.

Answers (2)