Updated on Kisan Patel
This tutorial will explain you how to convert Generic List into JSON string or serialize an object to JSON string in C#?
To convert Generic List into JSON string, First Create a Stream that either writes to the destination you wish to serialize then Create an instance of DataContractJsonSerializer
, using the type of the object that you wish to serialize as the constructor argument. Call WriteObject
(to serialize) using the object you wish to process as a method argument.
System.Runtime.Serialization
assemblies in order to use DataContractJsonSerializer.Here, we will use below class properties for creating Generic List.
public class Student { public int Id { get; set; } public string Name { get; set; } }
The following example serializes a Generic List using a MemoryStream
, prints out the resulting JSON.
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; namespace JSONTest { class Program { public static void Main(string[] args) { // Create a list of strings. ListmyList = new List () { new Student{Id= 1, Name = "Kisan"}, new Student{Id= 2, Name = "Ravi"}, new Student{Id= 3, Name = "Devang"} }; // Create memory stream - we will use this // to get the JSON serialization as a string. MemoryStream memoryStream = new MemoryStream(); // Create the JSON serializer. DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(myList.GetType()); // Serialize the list. jsonSerializer.WriteObject(memoryStream, myList); // Get the JSON string from the memory stream. string jsonString = Encoding.Default.GetString(memoryStream.ToArray()); // Write the string to the console. Console.WriteLine(jsonString); Console.ReadLine(); } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
the above program generate below output…