简体   繁体   English

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

[英]ASP.NET - how do you change the way a JSON gets serialized?

I'm using ASP.NET to return a Json file with the following query: 我正在使用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);
    }

Here's the object that gets created: 这是创建的对象:

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; }
}
}

Which returns a JSON in this form: 它将以以下形式返回JSON:

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

Now, I want to edit either the Linq query or the Json serializer to output a Json like this: 现在,我想编辑Linq查询或Json序列化器以输出如下Json:

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

Notice the second Json is a single item, where the "name" key is now the value of "name" in the first Json. 请注意,第二个Json是单个项目,其中“名称”键现在是第一个Json中“名称”的值。 The "name" and "amount" keys are discarded. “名称”和“金额”键将被丢弃。 The "name" value is always unique, there can be no two billy's or timmy's, so that does not have to be taken into account. “名称”值始终是唯一的,不能有两个比利或蒂米,因此不必考虑。

How do I do this? 我该怎么做呢?

Try thus 因此尝试

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);
    }

put your query in a dictionary after serializes 序列化后将查询放入字典中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM