C# || How To Serialize & Deserialize JSON Using C#

The following is a module with functions which demonstrates how to serialize and deserialize Json using C#.

The following generic functions use Newtonsoft.Json to serialize and deserialize an object.

Note: To use the functions in this module, make sure you have the ‘Newtonsoft.Json‘ package installed in your project.

One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Manage NuGet Packages….‘, then type ‘Newtonsoft.Json‘ in the search box, and install the package titled Newtonsoft.Json in the results Tab.

Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!


1. Serialize – Integer Array

The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize an integer array to Json.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


2. Serialize – String List

The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize a list of strings to Json.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


3. Serialize – Custom Object List

The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize a list of custom objects to Json.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


4. Deserialize – Integer Array

The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to an integer array.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


5. Deserialize – String List

The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to a list of strings.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


6. Deserialize – Custom Object List

The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to a list of objects.

The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.


7. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


8. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply