ASP.NET - 如何更改JSON序列化的方式?

时间:2014-10-24 12:53:52

标签: javascript c# asp.net json

我正在使用ASP.NET通过以下查询返回Json文件:

public ActionResult getTransactionTotals(int itemID)
    {
        DBEntities db = new DBEntities();

        var query = from trans in db.Transactions
                    // Linq query removed for brevity
                        into selection
                        select new TransactionAmount
                        {
                            name = selection.Key,
                            amount = selection.Select(t => t.TransactionId).Distinct().Count()
                        };

        return Json(query.ToList(),JsonRequestBehavior.AllowGet);
    }

这是创建的对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OhYeah
{
public class TransactionAmount
{
    public String name { get; set; }
    public int amount { get; set; }
}
}

以这种形式返回JSON:

[{"name":"billy", "amount":5}, {"name":"timmy", "amount":18}]

现在,我想编辑Linq查询或Json序列化器来输出这样的Json:

[{"billy":5, "timmy":18}]

注意第二个Json是单个项目,其中“name”键现在是第一个Json中“name”的值。 “名称”和“金额”键被丢弃。 “名称”值始终是唯一的,不能有两个比利或蒂米,所以不必考虑。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

尝试这样

public ActionResult getTransactionTotals(int itemID)
    {
        DBEntities db = new DBEntities();

        var query = (from trans in db.Transactions
                    // Linq query removed for brevity
                        into selection
                        select new TransactionAmount
                        {
                            name = selection.Key,
                            amount = selection.Select(t => t.TransactionId).Distinct().Count()
                        }).ToDictionary(k => k.name, v => v.amount);



        return Json(query,JsonRequestBehavior.AllowGet);
    }

序列化

后将查询放入字典中