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

时间:2011-08-23 21:44:25

标签: 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<object> json = new List<object>();
json[0] = new List<object>();
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。

3 个答案:

答案 0 :(得分:11)

我会尝试使用匿名类型。

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]

答案 1 :(得分:1)

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

[
  { 
    "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的转换。

答案 2 :(得分:0)

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

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 ..这是避免错误的好方法。