Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)
You can use the C# dynamic
type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings.
JSON
The JSON string below is a simple response from an HTTP API call, and it defines two properties: Id
and Name
.
{"Id": 1, "Name": "biofractal"}
C#
Use JsonConvert.DeserializeObject<dynamic>()
to deserialize this string into a dynamic type then simply access its properties in the usual way.
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);var id = results.Id;var name= results.Name;
If you specify the type of the results
variable as dynamic
, instead of using the var
keyword, then the property values will correctly deserialize, e.g. Id
to an int
and not a JValue
(thanks to GFoley83 for the comment below).
Note: The NuGet link for the Newtonsoft assembly is http://nuget.org/packages/newtonsoft.json.
Package: You can also add the package with nuget live installer, with your project opened just do browse package and then just install it install, unistall, update, it will just be added to your project under Dependencies/NuGet
If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject
class. For example:
JToken token = JObject.Parse(stringFullOfJson);int page = (int)token.SelectToken("page");int totalPages = (int)token.SelectToken("total_pages");
I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.
Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET
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_pagesvar albums = x.albums;foreach(var album in albums){ var albumName = album.name; // Access album data;}