Reputation: 4462
I have a IList and I wanted to convert it to a JsonArray to return in method JsonResult. How could I do this ?
Note: I'm using Json.NET
trying.
public JsonResult findByCriterio(String criterio){
Empresa empresa = getEmpresa();
IList<CategoriaProduto> lista = new List<CategoriaProduto>();
if (criterio.Length >= 5){
lista = dao.findByCriterio(criterio, empresa);
}else{
lista = dao.findAll(empresa);
}
var jsonArray = JsonConvert.SerializeObject(lista, Formatting.Indented);
return Json(jsonArray);
}
Entity
[Serializable]
public class CategoriaProduto{
public virtual long id { get; set; }
public virtual String descricao { get; set; }
public virtual Empresa empresa { get; set; }
public CategoriaProduto(){
}
public override string ToString(){
return descricao;
}
}
Upvotes: 0
Views: 1429
Reputation: 129827
You are double-serializing your result by using both JsonConvert.SerializeObject()
and the Json()
MVC controller method. You either need to do this:
var jsonArray = JsonConvert.SerializeObject(lista, Formatting.Indented);
return Content(jsonArray, "application/json");
or this:
return Json(lista);
If you use the first method, you'll also need to change the return type of your controller method from JsonResult
to either ContentResult
or ActionResult
.
If you use the second method, be aware it does not use the Json.Net serializer internally (it actually uses JavaScriptSerializer
), so it won't honor any Json.Net settings or attributes that you may be using.
Upvotes: 3