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:
p.name =
"John";
p.age =
42;
2.
Serialize the
Person
object to a memory stream using the DataContractJsonSerializer.
DataContractJsonSerializer
ser = new DataContractJsonSerializer(typeof(Person));
4.
Show the JSON output.
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(p2.name);
Console.Write(",
age=");
Comments
Post a Comment