JSON serialization in C#

Serialization is an important process which allows the developer to encode application objects to a text format that can be saved to file, database or sent to a remote server. On the contrary, deserialization allows the developer to decode back this text into an object. In this post, I would like to show you a quick tip on how to serialize objects in any .NET application.

Nowadays, JSON format is one of the most used in mobile application development and unlike XML’s object representations consumes less space, which can be useful especially when sending data to the server.

DataContract

First of all, mark your class with [DataContract] attribute and it’s members you want to be stored with [DataMember] attribute.

[DataContract] 
public class Car {      
    [DataMember]     
    public string Name { get; set; }     

    [DataMember]     
    public int Seats { get; set; } 
}

Helper class

Create help class JsonHelper.cs which will provide encoding functions.

public static class JsonHelper
     {
         public static T FromJson(string json)
         {
             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
             using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
             {
                 return (T)ser.ReadObject(stream);
             }
         }

        public static string ToJson(T obj)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, obj); var jsonArray = ms.ToArray();
                return Encoding.UTF8.GetString(jsonArray, 0, jsonArray.Length);
            }
        }

Convert an object to JSON string

var car = new Car(); var json = JsonHelper.ToJson(car);

Convert JSON string back to an object.

var car = JsonHelper.FromJson<Car>(json); 

That’s all! Hope it helps.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *