Do you want to serialize an collection in your C# application?. Json.NET supports this functionality with ease.
The Collection can be an Array , Dictionary or List. You need to simply pass collection to the JsonConvert.SerializeObject static method which would serialize the collection and return you the Json string.
How to Serialize a Collection in C# using JSON.NET ?
For example , assume that you want to serialize the employee class as shown below.
public class Employee { public string Name { get; set; } public bool IsPermanent { get; set; } // Employee can belong to multiple departments public List<string> Departments { get; set; } }
You will create the List<Employee> and fill it with the values as shown below.
List<Employee> employees = new List<Employee>(); //Employee 1 Data Employee emp1 = new Employee(); emp1.Name = "Employee 1"; emp1.IsPermanent = true; emp1.Departments = new List<string> {"Technology", "Design"}; employees.Add(emp1); // Employee 2 Data Employee emp2 = new Employee(); emp2.Name = "Employee 2"; emp2.IsPermanent = false; emp2.Departments = new List<string> {"Technology"}; employees.Add(emp2);
Once the List<Employee> data is available , pass it to the JsonConvert.Serialize method as shown below.
// Convert the collection to Json string string jsonData = JsonConvert.SerializeObject(employees);
Below is the complete code snippet that is used for serializing the collection in this blog post.
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace ACConsoleCSharp { class Program { static void Main(string[] args) { var jsonData = SerializeCollection(); Console.WriteLine("Serialized Data : \n" + jsonData); Console.ReadLine(); } public static string SerializeCollection() { List<Employee> employees = new List<Employee>(); //Employee 1 Data Employee emp1 = new Employee(); emp1.Name = "Employee 1"; emp1.IsPermanent = true; emp1.Departments = new List<string> {"Technology", "Design"}; employees.Add(emp1); // Employee 2 Data Employee emp2 = new Employee(); emp2.Name = "Employee 2"; emp2.IsPermanent = false; emp2.Departments = new List<string> {"Technology"}; employees.Add(emp2); // Convert the collection to Json string string jsonData = JsonConvert.SerializeObject(employees); return jsonData; } } public class Employee { public string Name { get; set; } public bool IsPermanent { get; set; } // Employee can belong to multiple departments public List<string> Departments { get; set; } } }
Leave a Reply