Wednesday, April 19, 2023

What is JSON, and how do you serialize and deserialize it in .NET Core?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is commonly used for transmitting data between a client and a server over the web.

In .NET Core, you can use the System.Text.Json namespace to serialize and deserialize JSON. Here's an example:

using System.Text.Json;

// Serialize an object to JSON
var person = new Person { Name = "John Smith", Age = 30 };
var json = JsonSerializer.Serialize(person);

// Deserialize JSON to an object
var person2 = JsonSerializer.Deserialize<Person>(json);

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 

 
In the above code, we first create a Person object and serialize it to JSON using the JsonSerializer.Serialize method. We then deserialize the JSON back to a Person object using the JsonSerializer.Deserialize method.

Note that the Person class must have public properties with getter and setter methods for the serialization and deserialization to work.

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.