我有一个查询返回如下内容:
- 对象|数量|
- 随机名称_1|5|
- 随机名称_2|3|
我想退回一个像这样的j-son
{"Success": true, "Message": "Total rows 8", "Data": { "Random_Name_1": {"QTY": 5 ... }, "Random_Name_2": {"QTY": 3 ... } } }
如何在ASP.NET MVC4上制作的web API中实现这一点?
你可以试试这个:
// your data
var q = new[]
{
new {OBJECT = "Random_Name_1", QTY = 5, TYPE = "A"},
new {OBJECT = "Random_Name_2", QTY = 3, TYPE = "B"},
new {OBJECT = "Random_Name_3", QTY = 8, TYPE = "B"}
};
// construct the object
var obj = new
{
Success = true,
Message = string.Format("Total rows {0}", q.Count()),
Data = q.ToDictionary(
item => item.OBJECT,
item => item.GetType().GetProperties()
.Where(p => p.Name != "OBJECT")
.ToDictionary(p => p.Name, p => p.GetValue(item, null)))
};
// serialize the object (note that you don't need to do that from web api)
var json = JsonConvert.SerializeObject(obj);
注意,如果你已经知道数据的结构(即列),那么你可以通过避免反射来提高它的效率。平均值:
var obj = new
{
Success = true,
Message = string.Format("Total rows {0}", q.Count()),
Data = q.ToDictionary(
item => item.OBJECT,
item => new { item.QTY, item.TYPE })
};
以下是我解决它的方法,周一我可能会将其更改为反射式。。
var x = tw.spCall(type).ToList();
if (x.Count() == 0)
return new { Success = false, Message = "No data!" };
DataSet temp = new DataSet();
foreach (var y in x) {
if (temp.Tables[y.EQUIPMENT] == null) {
temp.Tables.Add(y.EQUIPMENT);
temp.Tables[y.EQUIPMENT].Columns.Add("id_key");
temp.Tables[y.EQUIPMENT].Columns.Add("PartNumber");
...
};
DataRow row = temp.Tables[y.EQUIPMENT].Rows.Add();
row.SetField("id_key",y.id_key);
row.SetField("PartNumber",y.PartNumber);
...
}
return JsonConvert.SerializeObject(temp, Newtonsoft.Json.Formatting.None);