Delen via


JSON Serialization

Download sample

This sample demonstrates how to use the DataContractJsonSerializer to serialize and deserialize data in the JavaScript Object Notation (JSON) format. This serialization engine converts JSON data into instances of .NET Framework types and back into JSON data. DataContractJsonSerializer supports the same types as DataContractSerializer. The JSON data format is especially useful when writing Asynchronous JavaScript and XML (AJAX)-style Web applications. AJAX support in Windows Communication Foundation (WCF) is optimized for use with ASP.NET AJAX through the ScriptManager control. For examples of how to use Windows Communication Foundation (WCF) with ASP.NET AJAX, see the AJAX Samples.

Note

This sample requires that .NET Framework version 3.5 is installed in order to build and run. Visual Studio 2008 is required to open the project and solution files.

Note

The setup procedure and build instructions for this sample are located at the end of this topic.

The sample uses a Person data contract to demonstrate serialization and deserialization.

[DataContract]
    class Person
    {
        [DataMember]
        internal string name;

        [DataMember]
        internal int age;
    }

To serialize an instance of the Person type to JSON, create the DataContractJsonSerializer first and use the WriteObject method to write JSON data to a stream.

Person p = new Person();
//Set up Person object...
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);

The memory stream contains valid JSON data.

{“age”:42,”name”:”John”}

The sample demonstrates deserializing from JSON data into an object. You then rewind the stream and call ReadObject.

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

Examining the p2 object reveals that the JSON data has been deserialized correctly.

To set up, build and run the sample

  1. Build the solution JsonSerialization.sln as described in Building the Windows Communication Foundation Samples.

  2. Run the resulting console application.

© 2007 Microsoft Corporation. All rights reserved.