JSON is a format that encodes objects in a string. So serialization means to convert an object into that string, and deserialization is its inverse operation.
So we can say that suppose if we have an object like :
{foo: [1, 4, 7, 10], bar: "baz"}
Then, serializing into JSON will convert it into a string like the following:
'{"foo":[1,4,7,10],"bar":"baz"}'
Json.NET provides an excellent support for serializing and deserializing collections of objects. To serialize a collection like list, array and dictionary simply call the serializer with the object you want to get JSON for. Json.NET will serialize the collection and all of the values it contains.
The following code snippet shows how can you serialize a list of items.
Item i1 = new Item
{
Name = "itemA",
Price = 99rs,
ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
};
Item i2 = new Item
{
Name = "itemB",
Price = 12rs,
ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};
List<Item> items = new List<Item>();
items.Add(i1);
items.Add(i2);
string Serializedjson = JsonConvert.SerializeObject(items, Formatting.Indented);
You don't need the loop. But to use it you may need to install the Newtonsoft.Json
package first via NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console) :
PM> Install-Package Newtonsoft.Json
I would highly recommend to read this Json.NET documentation for more information on how to serialize and deserialize the collection of objects.
Note that if you are using .Net Core 3.0 or later version you can achieve the same by using the built in System.Text.Json
parser implementation as show below.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
You should also check this answer for more knowledge.