Using the Orcas JsonSerializer

One of the really cool features included in the Orcas bits is the integration between Microsoft AJAX 1.0 and WCF. My buddy Steve Maine has been doing an amazing job evangelizing this technology. One of the components that make possible the “WCF-Atlas” magic is the DataContractJsonSerializer. This is the component that serializes .NET objects into a JSON representation and deserializes JSON data back into .NET objects. Using the DataContractJsonSerializer is fairly similar to using other .NET serializers. Let’s take the following WCF Data Contract as an example:

    [DataContract]

    public class Sample

    {

        [DataMember]

        public int Field1;

        [DataMember]

        public string Field2;

        [DataMember]

        public bool Field3;

    }

 

The following code serializes an instance of that contract in a JSON representation.

Sample obj = new Sample();

 obj.Field1 = 111;

 obj.Field2 = "test";

 obj.Field3 = true;

 FileStream stream = new FileStream(file path…, FileMode.OpenOrCreate);

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Sample));

serializer.WriteObject(stream, obj);

stream.Close();

 

This code produces the following JSON serialized format.

{"Field1":111,"Field2":"test","Field3":true}

 

The deserialization process is also very similar to the existing .NET serializers.

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

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Sample));

Sample  obj= (Sample)serializer.ReadObject(stream);

 

Simple and brilliant, like all good technologies.

7 Comments

Comments have been disabled for this content.