如何从C#序列化到JSON包含包含数组的列表的列表?

我希望从C sharp序列化为JSON。 我希望输出

[ [ { "Info": "item1", "Count": 5749 }, { "Info": "item2", "Count": 2610 }, { "Info": "item3", "Count": 1001 }, { "Info": "item4", "Count": 1115 }, { "Info": "item5", "Count": 1142 }, "June", 37547 ], "Monday", 32347 ] 

我在C#中的数据结构会是什么样子?

我会有类似的东西吗?

 public class InfoCount { public InfoCount (string Info, int Count) { this.Info = Info; this.Count = Count; } public string Info; public int Count; } List json = new List(); json[0] = new List(); json[0].Add(new InfoCount("item1", 5749)); json[0].Add(new InfoCount("item2", 2610)); json[0].Add(new InfoCount("item3", 1001)); json[0].Add(new InfoCount("item4", 1115)); json[0].Add(new InfoCount("item5", 1142)); json[0].Add("June"); json[0].Add(37547); json.Add("Monday"); json.Add(32347); 

? 我使用的是.NET 4.0。

我会尝试使用匿名类型。

 var objs = new Object[] { new Object[] { new { Info = "item1", Count = 5749 }, new { Info = "item2", Count = 2610 }, new { Info = "item3", Count = 1001 }, new { Info = "item4", Count = 1115 }, new { Info = "item5", Count = 1142 }, "June", 37547 }, "Monday", 32347 }; String json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objs); 

变量json现在包含以下内容:

 [[{"Info":"item1","Count":5749},{"Info":"item2","Count":2610},{"Info":"item3","Count":1001},{"Info":"item4","Count":1115},{"Info":"item5","Count":1142},"June",37547],"Monday",32347] 

这看起来很挑战,因为您正在返回异构数组。 对于这样的结构,你会有更好的运气:

 [ { "itemInfo": { "items": [ { "Info": "item1", "Count": 5749 }, { "Info": "item2", "Count": 2610 }, { "Info": "item3", "Count": 1001 }, { "Info": "item4", "Count": 1115 }, { "Info": "item5", "Count": 1142 } ], "month": "June", "val": 37547 }, "day": "Monday", "val": 32347 } // , { ... }, { ... } ] 

这种方式不是在每个槽中返回一个包含不同信息的数组,而是返回一个定义良好的对象数组。 然后,您可以轻松地为看起来像这样的类建模,并使用DataContractSerializer来处理到JSON的转换。

这可能不会对你想要实现的目标产生影响,但我认为我应该说明一点

 public class InfoCount { public InfoCount (string Info, int Count) { this.Info = Info; this.Count = Count; } public string Info; public int Count; } 

应该

 public class InfoCount { private string _info = ""; private int _count = 0; public string Info { get { return _info; } set { _info = value; } } public int Count { get { return _count; } set { _count = value; } } public InfoCount (string Info, int Count) { this.Info = Info; this.Count = Count; } } 

好吧,可能不需要设置_info和_count ..这是避免错误的好方法。