C# Serialization Guide Part2 – DataContract serializer

13 בApril 2014

תגובה אחת

Again as is at the previous post I gonna use the IserializeService Contract. And the same DataTransferObject

:So, define the Contract Service and your DTO

public class InternalData

    {

        public InternalData()

        {

        }


        public string internalValue;

    }

[DataContract]

    public class MyData

    {

        [DataMember]

        public int PublicID { get; set; }


        [DataMember]

        private int PrivateID = 9999;


        [DataMember]

        public string Value;


        [DataMember]

        public InternalData referenceData { get; set; }


        public MyData()

        {


        }


    }

public interface ISerializeService

    {

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

        object read(string path,Type t);

    }

Just noticed to the different, we have a special attribute DataContract and DataMember

The rule is simple, the class got DataContract, and any member who need to be serialized using DataMember, using this way we can easily mange the serialize member of the class

.And there is no different between public or private

:So the Implementation is like that

public class DataContractSerializeService : ISerializeService

    {

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

        {

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

            DataContractSerializer serializer =  new DataContractSerializer(type);


            serializer.WriteObject(writer, data);

            writer.Close();

            return true;

        }



        public object read(string path, Type t)

        {

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

            XmlDictionaryReader reader =

            XmlDictionaryReader.CreateTextReader(stream, new

                                      XmlDictionaryReaderQuotas());


 DataContractSerializer serializer = new DataContractSerializer(t);



 object ReturnsData = (object)serializer.ReadObject(reader, true);

            reader.Close();

            stream.Close();



   return ReturnsData;

        }

:The usage of this service is simple as we sow at previous post

serializer = new DataContractSerializeService();


serializer.write(dat, typeof(MyData));


yData GenertedData =

  (MyData)serializer.read("C://data2.txt", typeof(MyData));



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

Leave a Reply

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

תגובה אחת

  1. xetra13 בApril 2014 ב 8:35

    is there any other way to use dataContract ??
    what about Iserilizble Interface ?
    and this is the same interface of WCD isnt ??

    Reply