在 C# 中创建一个 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16898731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:05:14  来源:igfitidea点击:

Creating a JSON array in C#

c#json

提问by Nealon

Ok, so I am trying to send POST commands over an http connection, and using JSON formatting to do so. I am writing the program to do this in C#, and was wondering how I would format an array of values to be passed as JSON to the server.

好的,所以我正在尝试通过 http 连接发送 POST 命令,并使用 JSON 格式来执行此操作。我正在编写程序以在 C# 中执行此操作,并且想知道如何格式化要作为 JSON 传递到服务器的值数组。

Currently I have this:

目前我有这个:

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

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

Which translates to this in JSON:

这在 JSON 中转换为:

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

And I want to make an array, called items, where each element contains these three values. So it would essentially be an array of objects, in which the object contains a name, an index, and an optional field.

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

My guess was that it would be something along the lines of this:

我的猜测是,它会是这样的:

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

Which, if it were correct syntax, would translate to this in JSON:

其中,如果语法正确,将在 JSON 中转换为:

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

But, evidently I'm doing it wrong. Ideas? Any help is appreciated.

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

采纳答案by Dave Van den Eynde

You're close. This should do the trick:

你很接近。这应该可以解决问题:

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

If your source was an enumerable of some sort, you might want to do this:

如果您的来源是某种类型的可枚举,您可能想要这样做:

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

回答by Leri

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

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

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; }
}

Usage:

用法:

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

And in the result you won't have to change things several times if you need to change data-structure.

结果,如果您需要更改数据结构,您将不必多次更改内容。

p.s. Here'svery nice tool for complex jsons

ps这是一个非常好的复杂jsons工具

回答by Royi Namir

Also , with Anonymous types ( I prefer notto do this) -- this is just anotherapproach.

另外,对于匿名类型(我喜欢这样做)——这只是另一种方法。

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));
}

result :

结果 :

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

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

回答by santhosh

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() + "}
        }
    };