从HttpWebResponse反序列化JSON的方法

时间:2012-11-07 13:50:57

标签: c# asp.net json

我正试图找出在.NET 3.5中解析传入JSON服务器端的最佳方法。 我从JSON Formate的HttpWebResponse收到“title”。所以我必须检索每个标题并存储在数据库中。所以请提供检索每个标题的代码。

public class MyObject
{
    public ArrayList list { get; set; }
}

    var request = WebRequest.Create("https://api.dailymotion.com/videos?fields=description,thumbnail_medium_url%2Ctitle&search=Good+Morning");
    using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
    {
        using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText, typeof(MyObject));
        }
    }

我在myojb中收到了Title,但是如何从myojb中检索每个Title。

3 个答案:

答案 0 :(得分:10)

使用此段代码段通过Title对象获取dynamic

.NET 4.0及以上

JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
foreach (var o in obj["list"])
{
    var title = o["title"];
}

.NET 3.5及以下

JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
foreach (var o in (ArrayList)obj["list"])
{
    if (o is Dictionary<string, object>)
        var title = (o as Dictionary<string, object>)["title"];
}

使用Linq:

JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
var titles = ((ArrayList)obj["list"]).Cast<Dictionary<string, object>>()
                 .Select(s => s["title"].ToString()).ToArray<string>();

答案 1 :(得分:4)

序列化为dynamic对象

using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objects = js.Deserialize<dynamic>(reader.ReadToEnd());
    foreach (var o in objects)
    {
        Console.WriteLine(o["title"]);
    }
}

答案 2 :(得分:0)

“我正在试图找出解析传入JSON的最佳方法”

我会用json.net。它很容易反序列化/序列化json数据。

看看这里:

How to post JSON to the server?