简体   繁体   English

LINQ C#到MVC中的JSON对象数组

[英]LINQ C# to Array JSON Object in MVC

My intention is to use LINQ query then return JSON for MVC controller. 我的意图是使用LINQ查询,然后为MVC控制器返回JSON。

format I want to achieve: 我要实现的格式:

[{ 
   "A" : {"Count": 2 },
   "B" : {"Count": 7 },
}]

or 要么

[{ 
   "A" : [{"Count": 2 }],
   "B" : [{"Count": 7 }],
}]

But so far I only can make it like this: 但是到目前为止,我只能这样实现:

[{ 
   {"MG":"A", "Count": 2 },
   {"MG":"B", "Count": 7 }
}]

And I try something like below, it get error 我尝试如下所示,但出现错误

Invalid anonymous type member declarator. 无效的匿名类型成员声明符。 Anonymous type members must be declared with a member assignment, simple name or member access. 必须使用成员分配,简单名称或成员访问来声明匿名类型成员。

public JsonResult groupByTable()
{
    IQueryable<tblSAPMessage> v = sapMessages();
    var data = v.GroupBy(g => g.MaterialGroup)
        .Select(g => new { g.Key.ToString() = new {
                    Count = g.Count()
                }});
    return Json(data, JsonRequestBehavior.AllowGet);
}

Appreciate if someone can point me to correct direction. 赞赏有人是否可以指出我正确的方向。 Thanks ! 谢谢 !

if i understand correctly you need dynamic property names. 如果我正确理解,则需要动态属性名称。 You could achieve it only using Expando Object 您只能使用Expando Object来实现

You could try something around these lines. 您可以尝试解决这些问题。

dynamic mytype = new ExpandoObject();
var data = v.GroupBy(g => g.MaterialGroup)
        .Select(g => (IDictionary<string, object>) mytype.Add(g.Key.ToString(),
        new {Count =  g.Count()}));

you could look at these answers for more inspiration Dynamic properties 您可以查看这些答案以获得更多灵感动态属性

you can use json.net / newtonsoft to create a json object 您可以使用json.net / newtonsoft创建一个json对象

using Json.net
var countObject = new JObject ();
countObject.Add("count",2);
var jsonObject = new JObject();
jsonObject.Add("a", countObject);

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

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