获取json数组,空指针引用异常

时间:2013-02-11 04:41:29

标签: json windows-phone-7 nullreferenceexception

{"names":["name1","name2","name3","name4"]}

我需要获取它并在列表中显示它们。我正在做的是

public class brand
{  public string Name
    { get; set; }
}

public class brands
{  public list<brand> Names
    { get; set; }

}

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        getdata();
    }

    private void getdata()
    {
        string uri = "URL";
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));

        req.BeginGetResponse(new AsyncCallback(show), req);
    }

    private void show(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

        StreamReader stream1 = new StreamReader(response.GetResponseStream());


         string s1 = stream1.ReadToEnd();
         var ser = new DataContractJsonSerializer(typeof(brands));
         var stream = new MemoryStream(Encoding.Unicode.GetBytes(s1));


          var bb = (brands)ser.ReadObject(stream);


          foreach (var ev in bb.Names)
            {
                textBlock1.Text = ev.Name.ToString();
            }
        }

这是我在阅读博客文章后做的。我得到了NullReferenceException。 请告诉我我做错了什么或替代方法。

1 个答案:

答案 0 :(得分:0)

首先学习如何解析JSON数据。将此视为json字符串。

String jsonData = @"{""names"":[""name1"",""name2"",""name3"",""name4""]}";

var brands = JsonConvert.DeserializeObject<Brands>(jsonData);
foreach (var item in brands.names)
        {
            Console.WriteLine(item);
        }

您的品牌类在哪里

public class Brands
    {
        public List<string> names { get; set; }
    }

以上代码解释了如何解析json数据。现在,从Web服务获取json数据,因为您的请求不是POST请求(似乎是从您的代码中获取),您可以使用简单的WebCleint。

void getData()
{
  WebClient webClient = new WebClient();
  webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
  webClient.DownloadStringAsync(new Uri("url"));
}

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{

    var brands = JsonConvert.DeserializeObject<Brands>(e.Result);
    foreach (var item in brands.names)
    {
        Console.WriteLine(item);
    }
}

查看此博客是否有任何其他疑问:Parsing JSON in a Windows Phone Application