4

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.

user1798345
  • 51
  • 1
  • 1
  • 2
  • 1
    use Dictionary in place of array list. OR you can deserialize it with object type first and then look at the data and create appropriate class – Prashant Lakhlani Nov 07 '12 at 13:53

3 Answers3

11

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>();
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
4

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"]);
    }
}
James
  • 80,725
  • 18
  • 167
  • 237
0

"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?

Community
  • 1
  • 1
Ademar
  • 5,657
  • 1
  • 17
  • 23