I know there are a few posts about Newtonsoft so hopefully this isn\'t exactly a repeat...I\'m trying to convert JSON data returned by Kazaa\'s API into a nice object of som
Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.
var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];
With the dynamic
keyword, it becomes really easy to parse any object of this kind:
dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
var page = x.page;
var total_pages = x.total_pages
var albums = x.albums;
foreach(var album in albums)
{
var albumName = album.name;
// Access album data;
}
I like this method:
using Newtonsoft.Json.Linq;
// jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();
You can now access anything you want using the dictObj
as a dictionary. You can also use Dictionary<string, string>
if you prefer to get the values as strings.
You can use this same method to cast as any kind of .NET object.
Also, if you're just looking for a specific value nested within the JSON content you can do something like so:
yourJObject.GetValue("jsonObjectName").Value<string>("jsonPropertyName");
And so on from there.
This could help if you don't want to bear the cost of converting the entire JSON into a C# object.
i craeted an Extionclass for json :
public static class JsonExtentions
{
public static string SerializeToJson(this object SourceObject) { return Newtonsoft.Json.JsonConvert.SerializeObject(SourceObject); }
public static T JsonToObject<T>(this string JsonString) { return (T)Newtonsoft.Json.JsonConvert.DeserializeObject<T>(JsonString); }
}
Design-Pattern:
public class Myobject
{
public Myobject(){}
public string prop1 { get; set; }
public static Myobject GetObject(string JsonString){return JsonExtentions.JsonToObject<Myobject>(JsonString);}
public string ToJson(string JsonString){return JsonExtentions.SerializeToJson(this);}
}
Usage:
Myobject dd= Myobject.GetObject(jsonstring);
Console.WriteLine(dd.prop1);
Dynamic List Loosely Typed - Deserialize and read the values
// First serializing
dynamic collection = new { stud = stud_datatable }; // The stud_datable is the list or data table
string jsonString = JsonConvert.SerializeObject(collection);
// Second Deserializing
dynamic StudList = JsonConvert.DeserializeObject(jsonString);
var stud = StudList.stud;
foreach (var detail in stud)
{
var Address = detail["stud_address"]; // Access Address data;
}