所以,我已经到处搜索了,在网上找到了一些解析JSON字符串并将信息保存到特定变量中的示例,但是我对C#和Windows Phone 7开发非常陌生(只做了一个星期,但是因为我很熟悉C ++,所以学得很快)。我不太明白我应该如何处理这个问题,所以我将给你要解析的代码和我到目前为止写的代码。
我已经使用 http://jsonlint.com/ 验证器验证了我的JSON信息。下面是我想要解析的位于网站上的JSON信息:
[
{
"id": 19019,
"model": "tester",
"fields":
{
"name": "thename",
"slot": 45,
"category": "thecategory"
}
}
]
以下是我尝试使用的代码,用于解析JSON信息并将其存储为变量,以便稍后在程序中调用该信息:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += (s, eargs) =>
{
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var theItem = (RootObject)serializer.ReadObject(eargs.Result);
myTextBlock.Text = theItem.pk.ToString();
};
client.OpenReadAsync(new Uri("http://www.example.com/i/19019/json"));
}
}
public class RootObject
{
public int pk { get; set; }
public string model { get; set; }
public Item item { get; set; }
}
public class Item
{
public string name { get; set; }
public int slot { get; set; }
public string category { get; set; }
}
}
就这段代码而言,myTextBlock是我在Windows Phone 7应用程序中用于显示文本的文本块,myButton是用户点击以显示文本的按钮(一旦修复此问题,我将以不同方式显示文本)。现在,每当我启动此代码时,它可以正常初始化应用程序,但当我单击按钮时,它会给出一个InvalidCastException was unhandled错误,具体信息为When casting from a number, the value must be a number less than infinity.,错误出现在以下代码处:
var theItem = (RootObject)serializer.ReadObject(eargs.Result);
我希望提供足够的信息来帮助我解决这个问题。我更喜欢使用默认内置在Windows Phone 7 SDK中的库,但如果我尝试做的事情可以使用像JSON.NET或其他兼容库这样的外部库更好地处理,那么如果您提供适当的学习链接,我愿意学习。感谢您能给予的任何帮助。
干杯!