解析Windows手机的简单JSON数据

时间:2014-05-03 13:16:02

标签: c# json windows-phone-8

我在尝试解析一些json数据时感到难过,这主要是因为它比我以前处理过的更简单。所以这就是JSON的样子:

[ { "guid" : "782ba9b2-be03-4e1c-884c-a862a9d80bc7",
    "id" : 1016,
    "message" : "test",
    "tag" : "test",
    "username" : "asd"
  },
  { "guid" : "08aa59ca-af56-4a60-9304-e96a86d4832d",
    "id" : 1012,
    "message" : "test",
    "tag" : "test",
    "username" : "123"
  },
  { "guid" : "08aa59ca-af56-4a60-9304-e96a86d4832d",
    "id" : 1011,
    "message" : "test",
    "tag" : "test",
    "username" : "12"
  },
  { "guid" : "08aa59ca-af56-4a60-9304-e96a86d4832d",
    "id" : 1010,
    "message" : "test",
    "tag" : "test",
    "username" : "1"
  }
]

这是我目前的代码:

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string json = e.Result;
                if (!string.IsNullOrEmpty(json))
                {
                    GroupMessages results = JsonConvert.DeserializeObject<GroupMessages>(json);
                    JObject jo = new JObject();
                    jo = JObject.Parse(e.Result);
                    List<GroupMessages> contentList = new List<GroupMessages>();
                    JArray items = (JArray)jo[""];
                    int count = 0;
                    while (count < items.Count)
                    {
                        GroupMessages content = new GroupMessages();
                        tcUsername = items[count]["username"].ToString();
                        tcMessage = items[count]["message"].ToString();
                        tcGuid = items[count]["guid"].ToString();
                        tcTag = items[count]["tag"].ToString();

                        content.username = tcUsername;
                        content.message = tcMessage;
                        content.guid = tcGuid;
                        content.tag = tcTag;

                        contentList.Add(content);
                        count++;
                    }
                    generalList.ItemsSource = contentList.ToList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Data.ToString());
            }

        }

并且我认为我知道错误在哪里:

JArray items = (JArray)jo[""];

由于我曾与之合作的大多数json都是{“结果”:[info here]},我不确定该放什么。把它留空是导致它不起作用,所以我不确定我是如何解决这个问题的。

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

使用JToken获取部分结果。

JToken jt = JToken.Parse(e.Result);
JArray items = (JArray)jt;

答案 1 :(得分:0)

您获得了JSON数组,因此请使用JArray.Parse

//  jo = JObject.Parse(e.Result);
List<GroupMessages> contentList = new List<GroupMessages>();
JArray items = JArray.Parse(e.Result);