Working with JSON in C#

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

It is easy to read and write data.

It is easy for machines to parse and create.

The JavaScript Programming Language is based on the ECMA-262 subset.

JSON is a completely language-independent data transfer format.

It is used in all languages such as C++, C#, Java, JavaScript, Perl, and Python.

These features make JSON an ideal data exchange language.

Below is a sample JSON data structure.

Working with JSON in C#

In the C# programming language, the use of JSON (JavaScript Object Notation) is quite common and is often used to communicate with web services. JSON represents data in an easily readable and understandable format.

To use JSON data in C# program, Newtonsoft.Json package must be added to your project first. It comes in the SDK by default in Asp.Net Core. If you don't have it in your project, you can download it from Nuget. This package is used to convert JSON data to C# objects.

You can use the DeserializeObject() method of the JsonConvert class to convert JSON data into C# objects. This method converts a JSON data array to a C# object. The following example converts a JSON data array to a C# object:

First of all, I will create the class named Member on the C# side.

To be able to use it in C#, Newtonsoft.Json namespace must be attached to your project first. It is currently available as version 12.0.2, but it is a library that is constantly improving itself. You can find detailed information about Newtonsoft here.

Link: https://www.newtonsoft.com/json

In the example, let's convert the list of Member type to JSON array.

When we send a request to the Get method, we will see that our data has changed to the JSON array.

Reading JSON Data with C#

First, let's convert a string data in JSON format into a list of type Member. The codes are as follows.

When we send a request to the sample method, our output is as follows.

I hope it was useful.