views:

230

answers:

2

I have a simple object that is deserialized from JSON into a server-side object.

JSON:

{
   name             : 'ObjectName',
   host             : 'http://localhost',
   ImagesPath       : '/Images/'
}

On the server side, the above JSON code gets deserialized into this C# object via System.Web.Script.Serialization.JavaScriptSerializer:

public class InfoObject
{
    public string Name { get; set; }
    public string Host { get; set; }
    public string ImagesPath { get; set; }
}

Currently the above works fine, but I was thinking of adding a lot of properties to it. I want to add sub-objects to hold the extra data so that all the properties are not all in one long class.

Sub-object object:

public class TestSubObject
{
     public string TestString { get; set; }
}

So that the new C# object looks like:

public class InfoObject
{
    public string Name { get; set; }
    public string Host { get; set; }
    public string ImagesPath { get; set; }
    public TestSubObject MoreInformation {get;set;}
}

But the problem is that I don't know how to represent the initialization of a sub-object property in JSON. Maybe I missed something obvious, but google searches did not immediately yield an answer.

I tried:

{
    name             : 'ObjectName',
    host             : 'http://localhost',
    ImagesPath       : '/Images/',
    MoreInformation.TestString : 'hello world'
}

But no dice, so how do I correctly write the above in JSON?

+5  A: 

You can write it like this:

{
    Name             : 'ObjectName',
    Host             : 'http://localhost',
    ImagesPath       : '/Images/',
    MoreInformation  : {TestString : 'hello world'}
};

// And to access the nested object property:
obj.MoreInformation.TestString
CMS
Thanks, this was the answer I was looking for
Mark Rogers
+1  A: 

JSON itself is an "object" notation, just put another object inside the "object"

{
   key: value,
   key2 : { inner_key : value, inner_key2 : value }
}

As you can see, the expression { ... } yields an object

hasen j