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.

Published Thursday, May 10, 2007 8:44 PM by gsusx
Filed under: ,

Comments

# re: Using the Orcas JsonSerializer

That is clean! Me likes!

Thursday, May 10, 2007 8:57 PM by Ryan Anderson

# re: Using the Orcas JsonSerializer

can't agree with you more

Thursday, May 10, 2007 10:50 PM by C#

# re: Using the Orcas JsonSerializer

Nice one!

How can I serialize an object to a string instead of a file though?

Monday, October 22, 2007 12:25 PM by Leon

# re: Using the Orcas JsonSerializer

Using the orcas jsonserializer.. WTF? :)

Thursday, March 24, 2011 11:11 AM by weblogs.asp.net

# re: Using the Orcas JsonSerializer

I am eager of learning Flash, is there any paragraph associated to Flash, if all right, then please post it, thanks.

Tuesday, July 10, 2012 3:13 AM by Antonettee Masaitisr

# re: Using the Orcas JsonSerializer

Furraelz? That's marvelously good to know.

Sunday, September 30, 2012 3:29 AM by Yumi

# re: Using the Orcas JsonSerializer

These tocpis are so confusing but this helped me get the job done.

Tuesday, October 2, 2012 12:49 AM by Damla