在C#中创建JSON数组 [英] Creating a JSON array in C#

查看:2522
本文介绍了在C#中创建JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

目前我有这个:

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

将其翻译成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.

我的猜测是,这可能与以下内容类似:

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")]}

如果语法正确,则会在JSON中将其翻译为以下内容:

Which, if it were correct syntax, would translate to this in 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.

推荐答案

您已经关闭.这应该可以解决问题:

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

这篇关于在C#中创建JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆