在C#中创build一个JSON数组

好的,所以我试图通过http连接发送POST命令,并使用JSON格式来完成。 我正在编写程序在C#中这样做,并想知道如何格式化一个值的数组作为JSON传递到服务器。

目前我有这个:

new {name = "command" , index = "X", optional = "0"}

这在JSON中转化为:

 "name": "command", "index": "X", "optional": "0" 

我想创build一个名为items的数组,其中每个元素都包含这三个值。 所以它本质上是一个对象数组,其中对象包含名称,索引和可选字段。

我的猜测是,这将是这样的:

 new {items = [(name = "command" , index = "X", optional = "0"), (name = "status" , index = "X", optional = "0")]} 

如果这是正确的语法,将在JSON中转换为这个:

 "items": [ { "name": "command", "index": "X", "optional": "0" }, { "name": "status", "index": "X", "optional": "0" } ] 

但是,显然我做错了。 想法? 任何帮助表示赞赏。

你很近 这应该做的伎俩:

 new {items = new [] { new {name = "command" , index = "X", optional = "0"}, new {name = "command" , index = "X", optional = "0"} }} 

如果您的源代码是某种types的枚举,您可能需要这样做:

 new {items = source.Select(item => new { name = item.Name, index = item.Index, options = item.Optional })}; 

您最好为每个项目创build一些类,而不是使用匿名对象。 而在你序列化的对象中,你应该有这些项目的数组。 例如:

 public class Item { public string name { get; set; } public string index { get; set; } public string optional { get; set; } } public class RootObject { public List<Item> items { get; set; } } 

用法:

 var objectToSerialize = new RootObject(); objectToSerialize.items = new List<Item> { new Item { name = "test1", index = "index1" }, new Item { name = "test2", index = "index2" } }; 

在结果中,如果需要更改数据结构,则不必多次更改。

ps 这是复杂的json 的非常好的工具

此外,与匿名types(我喜欢这样做) – 这只是另一种方法。

 void Main() { var x = new { items = new[] { new { name = "command", index = "X", optional = "0" }, new { name = "command", index = "X", optional = "0" } } }; JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly.... Console.WriteLine(js.Serialize(x)); } 

结果:

{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}

 new {var_data[counter] =new [] { new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "} } };