/// Sunday, December 4

JSON Serializer/Deserialier

I have a working JSON (JavaScript Object Notation) serializer/deserializer for .NET. I can marshall complex types between the browser and server using JSON. This is for my AJAX Behaviour.NET library but like all my stuff you're free to use under the terms of the license. This was not an easy task. JSON is typeless which makes it very difficult to deserialize into strongly typed language like C#. I resorted to encoding the type of an object or array (collection) into the document itself:

    "__objtype__" : "Test.Amelgy.Ajs.Json.Person, Test.Amelgy.Ajs",
    "Name" : null,
    "Sex" : "\u0000",
    "__arrtype__Pets" : "System.String[], mscorlib",
    "Pets" : [
    "__arrtype__Books" : "System.Collections.ArrayList, mscorlib",
    "Books" : [
            "__objtype__" : "Test.Amelgy.Ajs.Json.Book, Test.Amelgy.Ajs",
            "Author" : "Tom Archer",
            "Title" : "Inside C#"
            "__objtype__" : "Test.Amelgy.Ajs.Json.Book, Test.Amelgy.Ajs",
            "Author" : "GOF",
            "Title" : "Design Patterns"
    "Weight" : 160

This has potential for a security risk, but I'll give the end developer an option to encrypt the type and assembly. Deserializing is a matter of building C# code and using the CSharpCodeDom to compile it. Here's a sample of C# code generated by the deserializer. Still very readable, good for debugging.

namespace nsc2fc87b2d1d5450a8080dd6f0168da50 { class Foo { public object GetObject() {
Test.MGutz.Json.Person object0 = new Test.MGutz.Json.Person();
object0.Name = null;
object0.Sex = "\u0000";
System.String[] array1 = new System.String[2];
object0.Pets = array1;
array1[0] = "sam-sam";
array1[1] = "chili";
System.Collections.ArrayList array2 = new System.Collections.ArrayList();
object0.Books = array2;
Test.MGutz.Json.Book object3 = new Test.MGutz.Json.Book();
object3.Author = "Tom Archer";
object3.Title = "Inside C#";
Test.MGutz.Json.Book object4 = new Test.MGutz.Json.Book();
object4.Author = "GOF";
object4.Title = "Design Patterns";
object0.Weight = 160;
return object0; }}}

The only remaining issue is nested anonymous arrays. That'll be ugly cuz I think I'm too far in the parser and I'm using my JsonTextWriter which is not random access. A slight challenge is all.

    "__arrtype__nested" : "ArrayList, mscorlib : int[], mscorlib"
    "nested" = [
        [1, 2, 3]


Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?