如何从c#序列化一个包含数组的列表到JSON

本文关键字:数组 包含 一个 列表 JSON 序列化 | 更新日期: 2023-09-27 18:06:24

我希望从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。

如何从c#序列化一个包含数组的列表到JSON

我会尝试使用匿名类型。

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可能不需要。这是一个避免错误的好方法。