C# Serialization Guide Part 6 – JSON

27 בApril 2014

תגובה אחת

Json is a nice transmission protocol based simple text which is popular especially on web

.services , but C# could also serilize for Json format

The main benefit of using C# to Json is the javaScript – Ajax built in supported to deserialized

.those files

:So , lets get back to our serialization contract

public interface ISerializeService


        bool write(object data, Type type, string path);

        object read(string path, Type t);


,And we needs some data object to test

pay attention to DataContract and DataMember attributes


  public class MyData



      public int PublicID { get; set; }


      private int PrivateID = 9999;


      public string Value;


:Now the implementation will be as follow

public class JsonSerializerService : ISerializeService


        public bool write(object data, Type type, string path)


            FileStream writer = new FileStream(path, FileMode.Create);

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);

            serializer.WriteObject(writer, data);


            return true;


        public object read(string path, Type t)


            FileStream stream = new FileStream(path, FileMode.Open);

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(t);

            object ReturnsData = (object)serializer.ReadObject(stream);


            return ReturnsData;



:The serializer write into any stream and the file results is a standard Json format like that

{“PrivateID”:9999,”PublicID”:0,”Value”:null,” }

.Now this type of file could easily get read by JavaScript oriented platforms

:To test this code try to run this section or any similar

static void Main(string[] args)


            ISerializeService serializer;

            serializer = new JsonSerializerService();

            serializer.write(new MyData(), typeof(MyData), "c://data5.txt");

            MyData GenertedData = (MyData)serializer.read

                                      ("c://data5.txt",  typeof(MyData));


הוסף תגובה
facebook linkedin twitter email

Leave a Reply

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

תגובה אחת

  1. Pingback: C# Serialization Guide Part 11 – Json.Net | Until The Next Exception