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>();
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"]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With