Monday, August 10, 2020

How to Convert JSON String to C# Object and Vice Versa | Serialize and Deserialize

Here is a sample code to convert C# object to JSON string and JSON string to C# object. This process is also called as Serializing and Deserializing. You need to install the Newtonsoft.Json library using Nuget manager to do this very easily.

Sample code will use the following class and properties as C# object.
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
        public int Mark { get; set; }
    }

SERIALIZE :
using Newtonsoft.Json;
    var student = new Student()
    {
        Name = "Sachin",
        Age = 26,
        Department = "CSE",
        Mark = 790
    };
 var serializedString = JsonConvert.SerializeObject(student);
Serialized result will be,
"{\"Name\":\"Sachin\",\"Age\":26,\"Department\":\"CSE\",\"Mark\":790}"

DESERIALIZE :
using Newtonsoft.Json;
var jsonStr = "{\"Name\":\"Sachin\",\"Age\":26,\"Department\":\"CSE\",\"Mark\":790}";
var deserializedObject = JsonConvert.DeserializeObject<Student>(jsonStr);
Deserialized result will be,
    new Student()
    {
        Name = "Sachin",
        Age = 26,
        Department = "CSE",
        Mark = 790
    };

No comments:

Post a Comment