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

Answer from biofractal on Stack Overflow
🌐
Newtonsoft
newtonsoft.com › json › help › html › deserializeobject.htm
Deserialize an Object
string json = @"{ 'Email': 'james@example.com', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [ 'User', 'Admin' ] }"; Account account = JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email); // james@example.com
🌐
Newtonsoft
newtonsoft.com › json › help › html › serializingjson.htm
Serializing and Deserializing JSON
For simple scenarios where you want to convert to and from a JSON string, the SerializeObject and DeserializeObject methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer.
🌐
Newtonsoft
newtonsoft.com › json › help › html › DeserializeWithJsonSerializerFromFile.htm
Deserialize JSON from a file
// read file into a string and deserialize JSON to a type Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json")); // deserialize JSON directly from a file using (StreamReader file = File.OpenText(@"c:\movie.json")) { JsonSerializer serializer = new JsonSerializer(); Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie)); }
Top answer
1 of 12
296

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

2 of 12
278

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

🌐
Newtonsoft
newtonsoft.com › json › help › html › DeserializeCollection.htm
Deserialize a Collection
string json = @"['Starcraft','Halo','Legend of Zelda']"; List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string.Join(", ", videogames.ToArray())); // Starcraft, Halo, Legend of Zelda
🌐
Newtonsoft
newtonsoft.com › json › help › html › m_newtonsoft_json_jsonconvert_deserializeobject__1.htm
JsonConvert.DeserializeObject(T) Method (String)
Deserializes the JSON to the specified .NET type. Namespace: Newtonsoft.Json Assembly: Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db
🌐
Newtonsoft
newtonsoft.com › json › help › html › DeserializeCustomCreationConverter.htm
Deserialize with CustomCreationConverter
string json = @"{ 'Department': 'Furniture', 'JobTitle': 'Carpenter', 'FirstName': 'John', 'LastName': 'Joinery', 'BirthDate': '1983-02-02T00:00:00' }"; Person person = JsonConvert.DeserializeObject<Person>(json, new PersonConverter()); Console.WriteLine(person.GetType().Name); // Employee Employee employee = (Employee)person; Console.WriteLine(employee.JobTitle); // Carpenter
Find elsewhere
🌐
Newtonsoft
newtonsoft.com › json › help › html › M_Newtonsoft_Json_JsonSerializer_Deserialize.htm
JsonSerializer.Deserialize Method (JsonReader)
Deserializes the JSON structure contained by the specified JsonReader. Namespace: Newtonsoft.Json Assembly: Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › serialization › system-text-json › deserialization
How to deserialize JSON in C# - .NET | Microsoft Learn
You can implement custom converters to provide functionality that isn't supported by the built-in converters. If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:
🌐
Newtonsoft
newtonsoft.com › json › help › html › Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm
JsonConvert.DeserializeObject Method
DeserializeObject Method (String, Type, JsonSerializerSettings) Overload List · Top · See Also · JsonConvert Class · Newtonsoft.Json Namespace ·
🌐
C# Corner
c-sharpcorner.com › article › newtonsoft-json-deserialize-c-sharp-example
Newtonsoft JSON Deserialize in C# with Example
August 17, 2023 - Step 6. Create a new class, “module post,” for requesting json parse from the rest api client. Write the following program listing. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using System.Net; using System.IO; namespace newtonsoft_json { public class modulePost { public static string urlServer = "http://localhost/json/ws.php"; public void setURL(string url) { urlServer = url; } public string getURL() { return urlServer; } public string Post(string data) { string DataFromPHP = null; try { string url = getURL(); byte[] bu
🌐
Medium
jason-ge.medium.com › newtonsoft-json-serializing-deserializing-a5449d17d4bc
NewtonSoft.JSON Serializing/Deserializing | by Jason Ge | Medium
April 3, 2024 - using System; using Newtonsoft.Json; public class Program { public class Account { public string AccountType { get; set; } } public static void Main() { string account1Json = "{ \"ACcountType\": \"test account 1\" }"; string account2Json = "{ \"accountType\": \"test account 2\" }"; Account account1 = JsonConvert.DeserializeObject<Account>(account1Json); Account account2 = JsonConvert.DeserializeObject<Account>(account2Json); Console.WriteLine(account1.AccountType); Console.WriteLine(account2.AccountType); } }
🌐
Nebulaa IT Solutions
nebulaaitsolutions.com › blog › serialization-deserialization-of-json-objects-using-newtonsoft-json-in-c
Serialization/Deserialization of JSON objects using Newtonsoft.Json in C# - Nebulaa IT Solutions | Nebulaa IT Solutions
February 22, 2023 - Serialization/Deserialization of JSON objects using Newtonsoft.Json in C# JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for…
🌐
Medium
medium.com › @ieplt › comprehensive-guide-to-using-json-and-newtonsoft-json-in-net-ac67b7963e35
Comprehensive Guide to Using JSON and Newtonsoft.Json in .NET | by İbrahim Emre POLAT | Medium
June 14, 2024 - Let’s explore how to deserialize JSON into objects using Newtonsoft.Json. To deserialize JSON into a C# object, you can use the JsonConvert.DeserializeObject<T> method.
🌐
Dotnet Playbook
dotnetplaybook.com › home › deserializing json with c#
Deserializing JSON with c# - Dotnet Playbook
February 24, 2019 - This tutorial details how to deserialize* a JSON “string” into a c# object using JSON.net by Newtonsoft.
🌐
Newtonsoft
newtonsoft.com › json › help › html › serializingcollections.htm
Serializing Collections
string json = @"{""key1"":""value1"",""key2"":""value2""}"; Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); Console.WriteLine(values.Count); // 2 Console.WriteLine(values["key1"]); // value1
🌐
Newtonsoft
newtonsoft.com › json › help › html › serializationguide.htm
Serialization Guide
Note that if TypeNameHandling or PreserveReferencesHandling has been enabled for JSON arrays on the serializer, then JSON arrays are wrapped in a containing object. The object will have the type name/reference properties and a $values property, which will have the collection data. When deserializing, if a member is typed as the interface IList<T>, then it will be deserialized as a List<T>.
🌐
Newtonsoft
newtonsoft.com › json › help › html › M_Newtonsoft_Json_JsonConvert_DeserializeObject_1.htm
JsonConvert.DeserializeObject Method (String, JsonSerializerSettings)
Deserializes the JSON to a .NET object using JsonSerializerSettings. Namespace: Newtonsoft.Json Assembly: Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › serialization › system-text-json › migrate-from-newtonsoft
Migrate from Newtonsoft.Json to System.Text.Json - .NET | Microsoft Learn
A value enclosed in single quotes results in a JsonException with the following message: ... Newtonsoft.Json accepts non-string values, such as a number or the literals true and false, for deserialization to properties of type string.