0
{"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。请告诉我我在哪里做错或做同样的替代方法。

4

1 回答 1

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);
        }

你的 Brands 课程是这样的

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

于 2013-02-11T06:02:26.077 回答