In C# programming, deserialization is a widely used method to transform JSON data into .NET objects. It serves as the opposite of serialization, aiding in extracting organized data from various sources like files, APIs, or databases.
The CSS code below defines the styling for a placeholder diagram, including a gradient background, border radius, padding, margin, and text alignment. It also specifies the styles for the icon and text within the placeholder diagram.
To conduct deserialization in C#, it is essential to import the System.Text.Json or Newtonsoft.Json namespace. When retrieving data from a file, the System.IO namespace is additionally employed to manage file operations.
Syntax:
It has the following syntax.
ClassName objectName = JsonSerializer.Deserialize< ClassName >( jsonString );
In this syntax,
- ClassName: It defines the name of the class for which the JSON data will be converted.
- objectName: It defines the name of the object that will store the deserialized data.
- JsonSerializer: It is a built-in class in the System.Text.Json namespace. It provides the method of serializing and deserializing JSON data.
- Deserialize<ClassName>: It is a generic method that converts the JSON string into an object of the specified class.
- JsonString: It is the input string that contains the JSON data to be deserialized.
C# Simple Deserialization Example
Let's consider an example to explain the process of deserialization in C#.
Example
using System;
using System.Text.Json;
namespace Deserialization
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class C# Tutorial
{
static void Main( string[] args )
{
string jsonString = @"{
""Id"": 1,
""Name"": "" Peterson "",
""Age"": 25
}";
Student ss = JsonSerializer.Deserialize<Student>( jsonString );
Console.WriteLine( " The Student Details are " );
Console.WriteLine( " The id is " + ss.Id );
Console.WriteLine( " The name is " + ss.Name );
Console.WriteLine( " The age is " + ss.Age );
}
}
}
Output:
The Student Details are
The id is 1
The name is Peterson
The age is 25
Explanation:
In this illustration, we showcase the process of deserialization in C#. Initially, a class comprising of three attributes - Id, Name, and Age - is established. Within the Main method, the JSON string is supplied to the JsonSerializer.Deserilizer.Deserialize(jsonString) function, transforming the JSON information into a Student instance denoted as ss. Subsequently, the Console.WriteLine function is employed to display the result.
JSON represents JavaScript Object Notation, serving as a lightweight format for exchanging data that is both human-readable and writable. JSON, a text-based structure, is universally adaptable across various programming languages. Its common application in web development involves facilitating data transmission between servers and clients.
JSON has the following styles:
- Object
- Array
- String
Here, we will explore these JSON ideas individually.
1) Object (in JSON)
The item within JSON serves as a foundational data format that illustrates an assortment of key-value pairs without a specific order. It is surrounded by curly brackets {}. Every key is a string followed by a colon (:), with each key linked to a corresponding value.
Syntax:
It has the following syntax.
{
"key1": "value1",
"key2": "value2"
}
2) Array (in JSON)
An array within JSON is a sequential gathering of data items denoted by square brackets . This structure encapsulates an individual roster of components.
Syntax:
It has the following syntax:
[
"value1",
"value2",
"value3"
]
3) String (in JSON)
A JSON string is a series of Unicode characters enclosed within double quotation marks. Strings are frequently employed to depict textual values like names, messages, or identifiers within JSON datasets.
Syntax:
It has the following syntax:
{
"Name": "Johnson"
}
Error Handling in Deserialization
In C# coding language, implementing error-handling is crucial to develop resilient applications that handle external data inputs like JSON or XML. The most suitable error-handling strategy varies based on the specific serialization or deserialization method being used.
C# Error-handling Example in Deserialization
Let's consider an instance to demonstrate how error management works during deserialization in C#.
Example
using System;
using System.Text.Json;
public class C# Tutorial
{
public int Id {get; set;}
public string Name {get; set;}
public int Age {get; set;}
}
class TPT
{
static void Main()
{
string jsonString = @"{
""Id"": 1,
""Name"": ""Mehta"",
""Age"": ""Twenty-Two""
}";
try
{
C# Tutorial m = JsonSerializer.Deserialize<C# Tutorial>(jsonString);
Console.WriteLine("Deserialization successful!");
Console.WriteLine($"The id is {m.Id}");
Console.WriteLine($"The name is {m.Name}");
Console.WriteLine($"The age is {m.Age}");
}
catch (JsonException mx)
{
// Handle errors
Console.WriteLine("Error during deserialization!");
Console.WriteLine("Message: " + mx.Message);
}
}
}
Output:
Error during deserialization!
Message: The JSON value could not be converted to System.Int32. Path: $.Age | LineNumber: 3 | BytePositionInLine: 31.
Explanation:
In this instance, we define a class called Administration. This class outlines the format of the JSON entity containing three attributes: id, Name, and Age. Within the primary function, the script endeavors to convert a JSON string into an object within a try-catch block. If the JSON adheres to the class blueprint, the script displays the converted values. Notably, the Age attribute is mistakenly cast as a string despite being an integer, triggering an exception that results in an error message being displayed.
Nested JSON Object
In C#, a nested JSON refers to a JSON object that encloses another JSON object within it. This feature enables the representation of data in a hierarchical or structured format, enhancing clarity and organization.
Syntax:
It has the following syntax.
{
"Key1": "Value1",
"Key2": {
"SubKey1": "SubValue1",
"SubKey2": "SubValue2"
}
}
In this syntax:
The Key1 stores a basic value, while the Key2 encompasses a separate JSON object with its distinct keys and corresponding values.
Nested JSON Object Example in C#:
Let's consider an example to showcase the utilization of nested JSON objects in C#.
Example
using System;
using System.Text.Json;
public class Address
{
public string City {get; set;}
public string ZipCode {get; set;}
}
public class Teacher
{
public int Id {get; set;}
public string Name {get; set;}
public Address Address {get; set;}
}
class C# Tutorial
{
static void Main()
{
string jsonStr = @"{
""Id"": 1,
""Name"": ""Abhay"",
""Address"": {
""City"": ""Delhi"",
""ZipCode"": ""110001""
}
}";
Teacher tt = JsonSerializer.Deserialize<Teacher>(jsonStr);
Console.WriteLine("The Id is " + tt.Id);
Console.WriteLine("The name is " + tt.Name);
Console.WriteLine("The city is " + tt.Address.City);
Console.WriteLine("The zipCode is " + tt.Address.ZipCode);
}
}
Output:
The Id is 1
The name is Abhay
The city is Delhi
The zipCode is 110001
Explanation:
In the example given, we define two classes: Address and Teacher. Address class holds attributes like City and ZipCode, while the Teacher class comprises properties such as Id, Name, and an instance of the Address class. Within the Main function, a JSON string named jsonStr is constructed to represent a JSON object. Subsequent to deserialization, the deserialized value is outputted using the Console.WriteLine function.
Advantages of Deserializations in C#
Let's discuss some common advantages of deserialization in C#:
- We can easily recreate complex objects by reconstructing objects from data formats such as JSON, XML, or binary data.
- It allows us to smooth data transfer between systems, API, or application. It converts the serialized data into .NET objects.
- It helps to identify errors such as missing data, incorrect formats, or unexpected errors in the JSON or XML data.
- It helps in improving the readability of the code and understanding, which makes it comparatively easier to maintain and modify.
Conclusion:
In summary, deserialization is the typical method used to transform JSON data into .NET objects. It functions as the opposite process of serialization, enabling the reconstruction of objects from various structured data formats like JSON, XML, or binary data. This capability simplifies the recreation of intricate objects for developers.
C# Deserialization FAQs
1) What is deserialization in C#?
In C# programming, deserialization is a widely used method to transform JSON data into .NET objects. It serves as the opposite of serialization and is essential for fetching organized data from various sources like files, APIs, or databases.
2) Define JSON objects in C#?
JSON represents JavaScript Object Notation. It serves as a lightweight method for exchanging data that is user-friendly for both reading and writing. JSON functions as a textual format that is entirely free from any specific programming language dependencies.
3) What is the typical namespace utilized for JSON deserialization in C#?
The primary choices for JSON deserialization in C# include:
- Text.Json
- Json
4) Serialization and deserialization in C# involve the process of converting object instances into a format that can be stored, transmitted, or reconstructed later. The key difference lies in their functionalities:
- Serialization: This process converts objects into a stream of bytes to facilitate storage or transmission. It is commonly used when saving object states, transferring data over a network, or persisting data in databases. Serialization helps in maintaining the state of an object for future use.
- Deserialization: Deserialization, on the other hand, reverses the process by reconstructing objects from the serialized data. It involves reading the serialized data and converting it back into an object instance. Deserialization is crucial for retrieving data that was previously serialized, enabling the restoration of object states and structures.
The primary contrast between serialization and deserialization lies in their functionalities. Serialization involves transforming an object into a specific data format, whereas deserialization is the standard method for converting JSON data into .NET objects, representing the inverse operation of serialization.
5) Can we use the Nested JSON object in C#?
Yes, we have the option to employ the nested JSON object. It follows the syntax outlined below.
{
"Key1": "Value1",
"Key2": {
"SubKey1": "SubValue1",
"SubKey2": "SubValue2"
}
}
In this syntax:
The Key1 stores a basic value, while the Key2 houses a separate JSON object with its unique keys and corresponding values.