好吧,所以我有一个类似的类:
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;}
}
我也有一个List<Channels>
(总计约650 Channels
)
ROOT
通道包含大约6个通道,每个通道都包含,儿童等。
如您在Channel
的代码中所看到的,还有许多其他属性,在这种情况下,我不想序列化。也就是说,所有Data Contracts
已经在基类中定义了,我不/不能仅仅为此操作更改它们。
那么,您问我的问题是什么?我需要让List<Channels>
或List<NewType>
序列化与JSON
并维护树结构。
如果不可能,至少我将如何将List<Channels>
序列化为JSON
维护结构?
编辑:我正在使用Newtonsoft.Json
我个人建议将列表序列序列到频道...请考虑以下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不会解析"通道",因为整个对象都是类型的频道,并且"儿童"中的每个对象都是类型的通道。如果您要通过避免方法传递此JSON,则应使用所有JSON持久数据将其构建回C#结构。