How to create a data contract for the Person type?


using System;
using System.Runtime.Serialization;

[DataContract]

public class Person
{
    // This member is serialized.

    [DataMember]

    internal string FullName;

    // This is serialized even though it is private.

    [DataMember]

    private int Age;

    // This is not serialized because the DataMemberAttribute
    // has not been applied.
    private string MailingAddress;

    // This is not serialized, but the property is.
    private string telephoneNumberValue;

    [DataMember]

    public string TelephoneNumber
    {
        get { return telephoneNumberValue; }
        set { telephoneNumberValue = value; }
    }

To serialize an instance of type Person to JSON

1.       Create an instance of the Person type:

Person p = new Person();
p.name = "John";
p.age = 42;

2.       Serialize the Person object to a memory stream using the DataContractJsonSerializer.

MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));

3.       Use the WriteObject method to write JSON data to the stream.

ser.WriteObject(stream1, p);

4.       Show the JSON output.

stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Person object: ");
Console.WriteLine(sr.ReadToEnd());
 

To deserialize an instance of type Person from JSON

         1.      Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

stream1.Position = 0;
Person p2 = (Person)ser.ReadObject(stream1);

2.       Show the results.
Console.Write("Deserialized back, got name=");
Console.Write(p2.name);
Console.Write(", age=");


Comments