【问题标题】:json parsing using url in windows phone application在Windows Phone应用程序中使用url解析json
【发布时间】:2013-11-13 06:58:58
【问题描述】:

我要解析这个url:https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json?search=rahm并在模拟器中显示数据。

我的代码是:

WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(downloadAboutCompleted);
webClient.OpenReadAsync(new Uri("https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json?search=rahm"), c);

private void downloadAlbumCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error == null && !e.Cancelled)
    {
        using (StreamReader httpwebStreamReader = new StreamReader(e.Result))
        {
            var results = httpwebStreamReader.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(results):
            var json = JObject.Parse(results);
            System.Diagnostics.Debug.WriteLine(json):

            foreach (JObject array in json["meta"]["view"])
            {
                JObject obj = JObject.Parse(array.ToString());
                string id= (string)obj["id"];
                string name= (string)obj["name"];

                MessageBox.Show(name);
            }
        }
    }
}

但我在以下行中遇到错误:

foreach (JObject array in json["meta"]["view"])

错误是:An exception of type 'System.InvalidCastException' occurred in PhoneApp1.DLL but was not handled in user code

提前致谢。

【问题讨论】:

  • 您能否发布您的json 数据的一部分,以便了解结构的外观。它可能需要转换为 JArrayview 作为每个 JArray 元素的单独 JObject

标签: json windows-phone-7 windows-phone-8


【解决方案1】:

首先,我们不应该调试你的代码,应该。只需使用 F5 而不是 Ctrl+F5 运行您的应用程序,当引发异常时,检查代码和变量,您会发现错误。

所以,你知道错误是什么,它就在那里说:你正在做一个无效的演员。您不能在循环中将json["meta"]["view"] 的结果转换为JObject,因为右边的对象是JProperty 类型,而不是JObject type

只需将循环更改为:

foreach (JProperty property in json["meta"]["view"])

它应该可以工作。

请你下次尝试自己解决问题,你不能在这里问这么简单的问题。

【讨论】:

    【解决方案2】:

    您不能在 json["meta"]["view"] 中使用 foreach,因为它是您 URL 中的 Json 对象。

     JObject obj = json["meta"]["view"];
                    string id= (string)obj["id"];
                    string name= (string)obj["name"];
    
                    MessageBox.Show(name);
    

    效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2012-06-05
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多