Federal09
Federal09

Reputation: 649

Ignore Json data when property is missing

I tried to get the id Field

dynamic post = fb.Get("/" + radListControl2.SelectedItem + "/feed?fields=message");

int count = (int)post.data.Count;

for (int i = 0; i < count; i++)
{
    radListControl1.Items.Add(Convert.ToString(post.data[i].id));
}

It work and return this:

{
  "data": [
    {
      "id": "5xxx269_10151xxx50270", 
      "created_time": "2013-05-24T12:52:24+0000"
    }, 
    {
      "id": "5xxx69_101515xxxx270", 
      "created_time": "2013-05-21T19:57:57+0000"
    }, 
    {
      "message": "xxxxx", 
      "id": "xxx_1015157xxx270", 
      "created_time": "2013-05-21T19:44:07+0000"
    }, 
    {
      "id": "xxx", 
      "created_time": "2013-05-21T19:28:32+0000"
    }, 
    {
      "id": "5xx69_1015xxx75270", 
      "created_time": "2013-05-19T22:02:24+0000"
    }, 
    {
      "id": "52xxx269_1xxxx40270", 
      "created_time": "2013-05-18T09:31:42+0000"
    }, 
    {
      "message": "xxxx", 
      "id": "xxxx", 
      "created_time": "2013-05-17T22:59:49+0000"
    }, 

id xxx is inserted in radlistbox, but this code returns the same list

int count = (int)post.data.Count;

for (int i = 0; i < count; i++)
{
    radListControl1.Items.Add(Convert.ToString(post.data[i].message));
}

but radlistbox is empty, i need only field Message can you help me please?

Upvotes: 0

Views: 145

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

You can use hasOwnProperty to check for the existence of a property on an object

if (post.data[i].hasOwnProperty("message") {
    radListControl1.Items.Add(Convert.ToString(post.data[i].message));
}

Upvotes: 0

Chris Moutray
Chris Moutray

Reputation: 18379

Perhaps only add when there is a value...

for (int i = 0; i < count; i++)
{
    string message = post.data[i].message;

    if (string.IsNullOrEmpty(message)) 
        continue;

    radListControl1.Items.Add(Convert.ToString(message));
}

Upvotes: 1

Related Questions