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

# Jesus Rodriguez's WebLog : Using the Orcas JsonSerializer

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

# re: Using the Orcas JsonSerializer

That is clean! Me likes!

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

# re: Using the Orcas JsonSerializer

can't agree with you more

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

# re: Using the Orcas JsonSerializer

Nice one!

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

Wednesday, March 26, 2008 8:48 PM by ASPInsiders

# The Weekly Source Code 22 - C# and VB .NET Libraries to Digg, Flickr, Facebook, YouTube, Twitter, Live Services, Google and other Web 2.0 APIs

Someone emailed me recently saying that they couldn’t find enough examples in .NET for talking to the

Leave a Comment

(required) 
(required) 
(optional)
(required)