Way to Deserialize JSON from HttpWebResponse

I'm trying to figure out the best way to parse incoming JSON server-side in .NET 3.5. I am receiving "title" from HttpWebResponse in JSON Formate. so i have to retrieve each title and store in the database. so please provide the code for retrieving each 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));
        }
    }

I am receiving Title in the myojb but how to retrieve Each Title from myojb.


Use this piece of code snippet to get Title by using dynamic object.

.NET 4.0 and above

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

.NET 3.5 and below

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"];
}

Using 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>();

序列化成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"]);
    }
}

"I'm trying to figure out the best way to parse incoming JSON"

I would use json.net. Its so easy to deserialize/serialize json data.

Have a look here:

How to post JSON to the server?

链接地址: http://www.djcxy.com/p/45874.html

上一篇: 如何使用HttpClient发布JSON?

下一篇: 从HttpWebResponse反序列化JSON的方法