在JSON中表示子对象的正确语法是什么?

时间:2009-03-24 01:05:04

标签: c# javascript json serialization syntax

我有一个简单的对象,它从JSON反序列化为服务器端对象。

JSON:

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

在服务器端,上面的JSON代码通过System.Web.Script.Serialization.JavaScriptSerializer反序列化到这个C#对象中:

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

目前上述工作正常,但我想添加很多属性。我想添加子对象来保存额外的数据,以便所有属性都不在一个长类中。

子对象对象:

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

这样新的C#对象如下所示:

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

但问题是我不知道如何在JSON中表示子对象属性的初始化。也许我错过了一些明显的东西,但谷歌搜索没有立即得出答案。

我试过了:

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

但没有骰子,那么如何在JSON中正确编写上述内容?

2 个答案:

答案 0 :(得分:8)

你可以这样写:

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

// And to access the nested object property:
obj.MoreInformation.TestString

答案 1 :(得分:1)

JSON本身是一个“对象”符号,只是将另一个对象放在“对象”

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

如您所见,表达式{ ... }产生一个对象