MVC 4 and JsonResult format

て烟熏妆下的殇ゞ 提交于 2019-12-07 17:07:33

问题


have a problem with the result format of this code

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

this return a json:

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

But i need a json with this format:

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

What can i do?

Thanks a lot and sorry my english.


回答1:


Replace your return with:

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



回答2:


When you return a _JsonResult_ it takes the object and automatically formats this way

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

If you really need other format you could return a _ViewResult_ from your action, add a View and manually write the json. But for this especific format you could use something similar to the Garath's answer.




回答3:


You can also use this:-

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

Before call

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



回答4:


I do not know if this is possible to do with JsonResult, but you can use Json.NET and it's LINQ support (look on the "LINQ to JSON \ Creating Json", so your method will be something like

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


来源:https://stackoverflow.com/questions/15940397/mvc-4-and-jsonresult-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!