将httpweb响应中的json响应解析为listView数据绑定窗口

时间:2014-07-16 07:54:07

标签: c# json listview httpwebrequest windows-phone-8.1

我正在制作如下的http帖子

public async Task<string> HttppostJson()
    {
        // Create a request using a URL that can receive a post. 
        HttpWebRequest request = HttpWebRequest.Create("URL") as HttpWebRequest;

        // Set the Method property of the request to POST.
        request.Method = "POST";

        string post = "postData";

        byte[] byteArray = Encoding.UTF8.GetBytes(post.ToString());

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        //Write data into a stream
        using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
        {
            stream.Write(byteArray, 0, byteArray.Length);
        }

        // Pick up the response:

        using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            result = reader.ReadToEnd();
        }

        return result;
    }

这给了我一个JSON字符串作为输出。其中一小部分如下

{
  "id":20,
  "title":"Testing after phase 2 is shifted to server",
  "from":"Administrator",
  "sendername":"ABX",
  "day":"Tuesday",
  "dateofMonth":"20th",
  "month":"May",
  "year":2014,
  "date":"Tuesday, 20th May, 2014",
  "content":"Ready. Set. Go"

}

还有19个这样的块引用了每个&#34; id&#34;。我想反序列化对象并在列表视图中填充它们,只有&#34;标题&#34; &#34;来自&#34;来自所有20个通知应该在listView中看到。稍后会添加更多ID,因此我想制作listView动态,其中应包括新添加的ID和相应的&#34; title&#34; &#34;来自&#34;。所以listview应该看起来像这样

Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id

Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id

Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
                ..
                .. 
                ..

我是Windows应用开发的新手。所以需要一些帮助。

1 个答案:

答案 0 :(得分:0)

你可以制作电影课。 然后你可以使用newtonsoft的Json.NET库并使用JObject类。

您只需将json响应保存到字符串中,然后从JObject获取值并将其添加到列表中。

    string json = someJsonText
    JObject response = JObject.Parse(json);
    List<Movie> list = new List<Movie>();
    Movie first = new Movie();
    first.Title = response.GetValue("title");
    list.Add(first);

在foreach或句子中执行此操作以获取,创建和保存所有电影。