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.

有帮助吗?

解决方案

Replace your return with:

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

其他提示

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.

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

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");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top