【问题标题】:MVC 4 and JsonResult formatMVC 4 和 JsonResult 格式
【发布时间】:2013-04-11 03:47:25
【问题描述】:

这段代码的结果格式有问题

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

我能做什么?

非常感谢,对不起我的英语。

【问题讨论】:

  • 你想把你的列表转换成哈希吗?
  • 嗨,戴夫...是的,就是这样

标签: asp.net-mvc json jsonresult


【解决方案1】:

将您的退货替换为:

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

【讨论】:

    【解决方案2】:

    当您返回 _JsonResult_ 时,它会获取对象并自动以这种方式格式化

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

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

    【讨论】:

    • daniel,欢迎堆砌。希望你继续回答问题。但问问自己,这次你有没有增值?
    【解决方案3】:

    你也可以用这个:-

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

    【讨论】:

      【解决方案4】:

      我不知道这是否可能与 JsonResult 相关,但您可以使用 Json.NET 并且它支持 LINQ(查看“LINQ to JSON \ Creating 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");
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-18
        • 2019-04-30
        • 1970-01-01
        • 2014-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多