Deserialize Json To Object In C# - Parse JSON To Object

Sameer Saini March 04, 2022
Deserialize Json To Object In C# - Parse JSON To Object

In this blog post, we will learn how we can deserialize Json to an Object in C#.

We will use the System.Text.Json namespace to deserialize Json to an Object in C#.

 

Deserialize Json to Object In C# Using JsonSerializer

The static class JsonSerializer provides us the .Deserialize() method to deserialize a Json to object in C#.

 

Overloads:

The Deserialize method provides around six different overloads. The Deserialize method also takes an optional Type generic parameter.

 

Return:

The .Deserialize() method returns a nullable type that is the deserialized value of the Json value that was passed to the method.

 

Deserialize Json To Object In C# - Code Example

We will read a Json file and then deserialize it's value to a C# object.

We will create a Json value for an employee object that will have three property values.

{ "FirstName": "John", "LastName": "Doe", "Salary": 10000.50 }

We will read this Json value from a text file and then try to parse the value to an object.

var jsonEmployee = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "sample.json"));

Now, let's use the .Deserialize() method to deserialize this employee Json to an Employee Object.

var deserializedEmployee = JsonSerializer.Deserialize(jsonEmployee); if (deserializedEmployee != null) { Console.WriteLine(deserializedEmployee.FirstName); Console.WriteLine(deserializedEmployee.LastName); Console.WriteLine(deserializedEmployee.Salary); }

 

Output:

John Doe 10000.5

 

Deserialize Json To Object In C# - Case Insensitive

Now that we know how we can deserialize Json, we will use the JsonSerializerOptions and read a Json which is in camel casing but our C# properties in pascal case. We will use the PropertyNameCaseInsensitive option on the JsonSerializerOptions class and set it to true.

Let's change our Json employee slightly and change the casing on the properties of the Json to be camel case rather than pascal case as in the previous example.

{ "firstName": "John", "lastName": "Doe", "salary": 10000.50 }

var jsonEmployee = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "sample.json")); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }; var deserializedEmployee = JsonSerializer.Deserialize(jsonEmployee, options); if (deserializedEmployee != null) { Console.WriteLine(deserializedEmployee.FirstName); Console.WriteLine(deserializedEmployee.LastName); Console.WriteLine(deserializedEmployee.Salary); }

 

Output:

John Doe 10000.5