Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to Deserialize JSON from HttpWebResponse

Tags:

json

c#

asp.net

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.

like image 259
user1798345 Avatar asked Dec 06 '22 11:12

user1798345


2 Answers

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>();
like image 73
Furqan Safdar Avatar answered Dec 10 '22 03:12

Furqan Safdar


Serialize into a dynamic object

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"]);
    }
}
like image 42
James Avatar answered Dec 10 '22 02:12

James