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"}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With