2013-04-11 51 views
3

有这个代码的结果格式的问题MVC 4和JsonResult格式

public JsonResult getCategorias(int? id) 
{ 
    var res = from c in db.Categorias 
    where ((id.HasValue && c.CategoriaPadre == id.Value) || (!id.HasValue && c.CategoriaPadre == null)) 
    select new { id = c.Id, label = c.Descripcion }; 

    return this.Json(res, JsonRequestBehavior.AllowGet); 
} 

这个返回json

[{"id":21,"label":"Marketing3"},{"id":22,"label":"Marketing4"}]

但我需要一个json这种格式:

{"21":"Marketing3","22":"Marketing4"}

我该怎么办?

非常感谢和抱歉我的英语。

+0

ü要到列表转换成散列之前? – 2013-04-11 03:59:22

+0

嗨戴夫...是的,只是 – jotero 2013-04-11 04:02:53

回答

3

请以你的回报:当您返回一个_JsonResult_需要的对象并自动

var dictionary = res.ToDictionary(v => v.id, v => label); 
return this.Json(dictionary, JsonRequestBehavior.AllowGet); 
+0

+1为更好的.. :) – PSL 2013-04-11 04:17:42

0

我不知道这是可能的JsonResult做,但你可以用Json.NET和它的支持LINQ(望天“的LINQ to JSON \创建的Json”,所以你的方法是这样的

public JsonResult getCategorias(int? id) 
{ 
    var properties = from c in db.Categorias 
    where ((id.HasValue && c.CategoriaPadre == id.Value) || (!id.HasValue && c.CategoriaPadre == null)) 
    select JsonProperty(c.Id.ToString(), c.Descripcion); 

    var res = new JObject(properties.ToArray()); 

    return Content(res.ToString(), "application/json"); 
} 
2

格式化这样

{ 
     "Property1":"Value1", 
     "Property2"_"Value2", 
     ... 
    } 

如果你真的需要其他格式,你可以从你的动作中返回一个_ViewResult_,添加一个视图并手动编写json。但是对于这种特定的格式,你可以使用类似于Garath答案的东西。

+0

丹尼尔,欢迎来到堆栈。我希望你继续回答问题。但问问自己,你这次增加了价值吗? – 2013-04-11 04:14:57

1

您也可以使用此: -

public static KeyValuePair<string,string> KeyValue(YourClass obj) 
     { 
      return new KeyValuePair<string, string>(obj.id, obj.label); 
     } 

呼叫

Json(result.ConvertAll(i => KeyValue(i)), JsonRequestBehavior.AllowGet); 
+0

也是一个很好的答案。有点晚,但也许更合适。 – 2013-04-11 04:17:02