提问人:sanmeet 提问时间:2/11/2013 最后编辑:Bobrovskysanmeet 更新时间:2/11/2013 访问量:213
获取json数组,空指针引用异常
Fetching json array, null pointer refrence exception
问:
{"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
答:
0赞
nkchandra
2/11/2013
#1
首先了解如何解析 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);
}
}
查看此博客以了解任何其他疑问:在 Windows Phone 应用程序中解析 JSON
评论