如何创建在C#中JSON对象,其中属性名飞设置? [英] How do I create JSON objects in C# where the property names are set on the fly?
问题描述
我需要返回JSON对象是一个SQL查询的结果数组。所以我需要在在code动态创建的属性名称,以及该值的SQL查询可以是任何东西。
例如,SELECT名字,姓氏来自员工我要回:
{数据:
[{
FIRST_NAME:戴夫,
姓氏:蒂伦
},
{
FIRST_NAME:约翰,
姓氏:匠
}]
}
但接下来的查询可能是选择项目,价格,税收,ship_date从接单,并希望返回:
{数据:
[{
项目:高清电视,
价格:598.95
税:59.89
ship_date:2013年8月26日
},
{
项目:电缆,
价格:54.67
税:5.47
ship_date:2013年8月26日
}]
}
我怎样才能建立这个在C#,然后转换成JSON?
谢谢 - 戴夫
使用匿名类型,对于EX(使用 Json.Net 一>),
VAR JSON = JsonConvert.SerializeObject(
新 {
数据=新的[] {
新{NAME =A,姓=B},
新{名称=C,姓=D},
}
}
);
会给
{数据:[{名:一,姓:B},{名:C,姓: D}]}
修改
我需要一:B
VAR JSON = JsonConvert.SerializeObject(
新的字典<字符串,字符串>(){
{一个,B}
}
);
输出: {一:B}
EDIT2
和一个有趣的一个
VAR字典=新字典<字符串,字符串>(){
{一个,B},
{ 光盘 }
};
VAR JSON = JsonConvert.SerializeObject(
新{数据= dict.Select(X =>新建[] {X} .ToDictionary(KV => kv.Key,KV => kv.Value))}
);
输出: {数据:[{一:B},{C:D}]}
I need to return an array of JSON objects that is the result of an SQL query. The SQL query can be anything so I need to create the property names as well as the values on the fly in code.
For example, "select first_name, last_name from employees" I want to return:
{ "data":
[{
"first_name": "dave",
"last_name": "thielen"
},
{
"first_name": "john",
"last_name": "smith"
}]
}
But the next query could be "select item, price, tax, ship_date from orders and want to return:
{ "data":
[{
"item": "HD TV",
"price": "598.95"
"tax": "59.89"
"ship_date": "2013-08-26"
},
{
"item": "Cables",
"price": "54.67"
"tax": "5.47"
"ship_date": "2013-08-26"
}]
}
How can I build this up in C# and then convert to JSON?
thanks - dave
Use anonymous types, For ex (using Json.Net),
var json = JsonConvert.SerializeObject(
new {
data = new[]{
new{name="a",surname="b"},
new{name="c",surname="d"},
}
}
);
would give
{"data":[{"name":"a","surname":"b"},{"name":"c","surname":"d"}]}
EDIT
I need "a": "b"
var json = JsonConvert.SerializeObject(
new Dictionary<string, string>() {
{ "a","b" }
}
);
output: {"a":"b"}
EDIT2
And a funny one
var dict = new Dictionary<string, string>() {
{ "a","b" },
{ "c","d" }
};
var json = JsonConvert.SerializeObject(
new { data = dict.Select(x => new[]{x}.ToDictionary(kv => kv.Key, kv => kv.Value)) }
);
Output: {"data":[{"a":"b"},{"c":"d"}]}
这篇关于如何创建在C#中JSON对象,其中属性名飞设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!