就我个人而言,我建议将列表序列化为 Channels 数组...考虑以下 JSON 示例:
{
"Channel": {
"Guid": "27182d04-29d9-4760-86d5-484ba43cd9c6",
"Title": "FooBar",
"Parent": "52cfd532-6010-41c5-8fa9-f3bcbb97a630",
"Children": [
{
"Channel": {
"Guid": "27182d04-29d9-4760-86d5-484ba43cd9c6",
"Title": "FooBar",
"Parent": "52cfd532-6010-41c5-8fa9-f3bcbb97a630",
"Children": null
}
},
{
"Channel": {
"Guid": "27182d04-29d9-4760-86d5-484ba43cd9c6",
"Title": "FooBar",
"Parent": "52cfd532-6010-41c5-8fa9-f3bcbb97a630",
"Children": null
}
},
{
"Channel": {
"Guid": "27182d04-29d9-4760-86d5-484ba43cd9c6",
"Title": "FooBar",
"Parent": "52cfd532-6010-41c5-8fa9-f3bcbb97a630",
"Children": null
}
}
]
}
}
编辑:这是一个将编写此结构的小测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace JSONTest
{
class Program
{
static void Main(string[] args)
{
Channel c = new Channel();
c.Guid = Guid.NewGuid();
c.Parent = Guid.NewGuid();
c.Title = "FooBar";
c.Children = new List<Channel>();
Channel a = new Channel();
Channel b = new Channel();
a.Guid = Guid.NewGuid();
b.Guid = Guid.NewGuid();
a.Parent = Guid.NewGuid();
b.Parent = Guid.NewGuid();
a.Title = "FooBar_A";
b.Title = "FooBar_B";
c.Children.Add(a);
c.Children.Add(b);
/* Serialization happens here!! */
JavaScriptSerializer serializer = new JavaScriptSerializer();
string result = serializer.Serialize(c);
Console.WriteLine(result);
Console.Read();
}
}
public class Channel
{
public Guid Guid { get; set; }
public string Title { get; set; }
/* GOT A LOT MORE PROPERTIES IN THIS SPACE */
public Guid Parent { get; set; }
public List<Channel> Children { get; set; }
}
}
这是通过 JSONLint 后的测试结果
{
"Guid": "0e72c12c-a7a1-461a-8b84-8b17023e2e2f",
"Title": "FooBar",
"Parent": "d0943246-1adc-4208-bb3b-1249ffe5e7b4",
"Children": [
{
"Guid": "1cf413be-d6b5-405e-8308-7c6dfe817f9a",
"Title": "FooBar_A",
"Parent": "ecf14fce-c97d-46f5-890b-bab8ff99fb4a",
"Children": null
},
{
"Guid": "bd96e6d3-f247-4a0d-9147-92da19793e97",
"Title": "FooBar_B",
"Parent": "5cd3e765-23c2-4145-8b45-9964a7c66c54",
"Children": null
}
]
}
有效的 JSON!
编辑:我注意到的一件事是 JavaScriptSerializer 不解析“Channel”,因为整个对象都是 Channel 类型,而“Children”中的每个对象都是 Channel 类型。如果您要通过 Deserialize 方法传递此 JSON,则应将其构建回包含所有 JSON 持久数据的 C# 结构。