In today's guide, I'm going to cover the code required to serialise and deserialise your C# objects with JSON.NET. If you're new to .NET, one of the go-to Nuget packages that you will very likely use on most projects is JSON.NET. As the name implies, JSON.NET allows you to do all things JSON related. As part of its many features, JSON.NET provides a feature to serialise and deserialise JSON into C# objects. Huaazh 🎉🎉🎉
How To Install Json.NET
The first thing you'll need to do is install JSON.NET via NuGet:
In Visual Studio, on your solution, right-click on Manage Nuget Packages For Solution
, search for Newtonsoft.Json
and off you go!
How To Serialise An Object With Json.NET
The code to serialise objects is pretty easy. Let us say we have this class:
If you want to store an object(s) state within a database row, or a CSV file, you will need to convert that object into a string, so it can be stored easily. The simplest way to do this is to serialize the object into JSON and store the resulting JSON returned as a single string value. For example: Â
How To Deserialize An Object With Json.NET
If you want to reverse the process and convert that string back into a C# object, you can use DeserializeObject()
method, like so:
Serialise and deserialising is really as simple as that! With just a few lines of code, you can now convert your objects to JSON and back again! Happy Coding 🤘