当属性丢失时忽略Json数据

时间:2013-05-24 13:53:47

标签: json foreach

我试图获得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));
}

它起作用并返回:

{
  "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插入到radlistbox中,但此代码返回相同的列表

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

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

但是radlistbox是空的,我只需要字段消息你可以帮我吗?

2 个答案:

答案 0 :(得分:1)

也许只有在有值时添加......

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

    if (string.IsNullOrEmpty(message)) 
        continue;

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

答案 1 :(得分:0)

您可以使用hasOwnProperty检查对象上是否存在属性

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