C# JSON Serialization

C# Code Snippets JSON Serialization
Share:

About

In this code snippet, we will learn about JSON serialization in C#.

Serialization is when you take an object and convert it to a stream of bytes that can be then stored in a file, database or memory. This is useful if you want to store the state of your objects or send them over the network(for example an API). Of course, you can also deserialize a file/database entry back into an object.

Note: See also XML and binary serialization.

In this example, we will serialize and deserialize an object to/from JSON. I will only make a JSON string. To make a JSON file you simply write the string to the file like you would for any other text. At the end just make sure to save the file with the .json extension instead of .txt.

Let’s have a look at the code below to see how to perform JSON serialization.

First, a JSON library from Newsoft has to be installed otherwise we will get an error. The library will be installed with the Nuget package manager.
Open Nuget.
Look for Newsoft.json, select it, add it to the project and click install.
Confirm and wait for it to install.
No more errors.

Code:

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger