JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services.
This topic demonstrates how to serialize .NET type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of .NET types using theDataContractJsonSerializer. This example uses a data contract to demonstrate serialization and deserialization of a user-definedPersontype.
Normally, JSON serialization and deserialization is handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly - this is the scenario that this topic demonstrates.
Note |
---|
If an error occurs during serialization of an outgoing reply on the server or the reply operation throws an exception for some other reason, it may not get returned to the client as a fault. |
This topic is based on the JSON Serialization sample.
To define the data contract for a Person
Define the data contract forPersonby attaching the DataContractAttribute to the class andDataMemberAttribute attribute to the members you want to serialize. For more information about data contracts, seeDesigning Service Contracts.
[DataContract] internal class Person { [DataMember] internal string name; [DataMember] internal int age; }
To serialize an instance of type Person to JSON
Create an instance of thePersontype.
Person p = new Person(); p.name = "John"; p.age = 42;
Serialize thePersonobject to a memory stream using theDataContractJsonSerializer.
MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
Use the WriteObject method to write JSON data to the stream.
ser.WriteObject(stream1, p);
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
Deserialize the JSON-encoded data into a new instance ofPersonby using the ReadObject method of theDataContractJsonSerializer.
stream1.Position = 0; Person p2 = (Person)ser.ReadObject(stream1);
Show the results.
Console.Write("Deserialized back, got name="); Console.Write(p2.name); Console.Write(", age="); Console.WriteLine(p2.age);