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

标签 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 中正确编写上面的内容?

最佳答案

你可以这样写:

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

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

关于c# - 在 JSON 中表示子对象的正确语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/675815/

相关文章:

javascript - 测试对象数组中是否存在值

javascript - onChange 用下拉标题而不是值替换 img src

c# - 如何从反序列化的 json 重新填充 View 模型?

c# - Vb.net到C#.net

javascript - 如何在实时网页中用 mailto 链接替换电子邮件地址?

java - Java 应用程序中的 org.JSON.JSONException

php - Symfony 表格 : How to replace form class/retrieve all extra data?

json - 用 jq 解析嵌套的 json

c# - 如何将 CloudFX 与 Azure SDK 2.0 结合使用?

C# Azure 函数 : Can't use CloudQueue type as output binding