我有一个简单的对象,它从 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/