【问题标题】:What is the correct syntax to represent subobjects in JSON?在 JSON 中表示子对象的正确语法是什么?
【发布时间】:2010-10-15 02:51:04
【问题描述】:

我有一个从 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 写出上面的内容呢?

【问题讨论】:

    标签: c# javascript json serialization syntax


    【解决方案1】:

    你可以这样写:

    {
        Name             : 'ObjectName',
        Host             : 'http://localhost',
        ImagesPath       : '/Images/',
        MoreInformation  : {TestString : 'hello world'}
    };
    
    // And to access the nested object property:
    obj.MoreInformation.TestString
    

    【讨论】:

    • 谢谢,这就是我要找的答案
    【解决方案2】:

    JSON 本身是一个“对象”表示法,只需将另一个对象放在“对象”内即可

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多