Home > Exploring the CodeFluent Runtime > Exploring the CodeFluent Runtime: JsonUtilities – Part 2

Exploring the CodeFluent Runtime: JsonUtilities – Part 2

This post follows the “Exploring the CodeFluent Runtime: JsonUtilities” post, in which we introduced the JsonUtilities class as well as its Serialize method.

In addition to serializing objects, you can also use the class to deserialize JSON such as this:

string s = JsonUtilities.Serialize(new string[] { "1", "2" });
List<int> list = JsonUtilities.Deserialize<List<int>>(s);

Running the code above, you’ll get a list of integers out of the JSON string as expected.

Another cool feature is that the serializer, on top of serializing all types such as byte[], guid, long, etc., can serialize anonymous types, you don’t have to use strongly typed objects:

s = JsonUtilities.Serialize(new
    MyDateAtt1 = DateTime.Now,
    MyEnumAtt2 = UriKind.RelativeOrAbsolute,
    MyBytes = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF },
    MyGuidAtt = Guid.NewGuid()

And then, when deserializing, we can use a strong type such as the MyType class, declared as follows:

public class MyType
    public DateTime MyDateAtt1; // field support
    public Guid MyGuidAtt { get; set; } // guid support

And here’s the code deserializing our anonymous type into a MyType type:

MyType mt = new MyType();
JsonUtilities.Deserialize(s, mt, JsonSerializationOptions.Default | JsonSerializationOptions.UseReflection); // sets props & fields

Properties which don’t exists (e.g. MyEnumAtt2 and MyBytes) will be skipped without raising an error.
Carl Anderson

  1. No comments yet.
  1. March 7, 2012 at 1:49 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s