好的,所以我试图通过http连接发送POST命令,并使用JSON格式来执行此操作.我正在编写程序在C#中执行此操作,并想知道如何格式化要作为JSON传递给服务器的值数组.
目前我有这个:
new {name = "command" , index = "X", optional = "0"}
这在JSON中转换为:
"name": "command",
"index": "X",
"optional": "0"
Run Code Online (Sandbox Code Playgroud)
我想创建一个名为items的数组,其中每个元素都包含这三个值.所以它本质上是一个对象数组,其中对象包含名称,索引和可选字段.
我的猜测是,这将是这样的:
new {items = [(name = "command" , index = "X", optional = "0"),
(name = "status" , index = "X", optional = "0")]}
Run Code Online (Sandbox Code Playgroud)
如果它是正确的语法,将在JSON中转换为this:
"items":
[
{
"name": "command",
"index": "X",
"optional": "0"
},
{
"name": "status",
"index": "X",
"optional": "0"
}
]
Run Code Online (Sandbox Code Playgroud)
但是,显然我做错了.想法?任何帮助表示赞赏.
Dav*_*nde 88
你很亲密 这应该做的伎俩:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
Run Code Online (Sandbox Code Playgroud)
如果您的源是某种类型的可枚举,您可能希望这样做:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
Run Code Online (Sandbox Code Playgroud)
Ler*_*eri 36
您最好为每个项目创建一个类,而不是使用匿名对象.在对象中,你要序列化,你应该有这些项目的数组.例如:
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; }
}
Run Code Online (Sandbox Code Playgroud)
用法:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
Run Code Online (Sandbox Code Playgroud)
在结果中,如果需要更改数据结构,则不必多次更改内容.
Roy*_*mir 10
此外,与匿名类型(我宁愿没有这样做) -这仅仅是另一种做法.
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));
}
Run Code Online (Sandbox Code Playgroud)
结果:
{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}
归档时间: |
|
查看次数: |
153624 次 |
最近记录: |