Reputation: 2035
I have MVC controller method which should return json string.
public JsonResult myMethod()
{
....
return Json(new { success = true, data = myObject });
}
It works. But column order of myObject is not the same as defined. (Json by definition returns unordered set of name/value pairs)
So, I have used Newtonsoft and on my class I have defined sort order like:
public class myObject{
[JsonProperty(Order = 0)]
public int id { get; set; }
[JsonProperty(Order = 1)]
public string name { get; set; }
}
And in MVC controller have to change method to return string instead of JsonResult (I don't know how to use newtonsoft to return jsonResult). And then I return string:
return "{ success = true, data = " + Newtonsoft.Json.JsonConvert.SerializeObject(myObject) + "}";
It works, string has correct column order, but ajax method doesn't recognize this string as json. So, what would be the best solution? How to return jsonResult from newtonsoft instead of json string?
Upvotes: 6
Views: 4675
Reputation: 21
If you want to use newtonsoft change return type to ContentResult
new ContentResult() { Content = JsonConvert.SerializeObject(result), ContentType = "application/json" };
Upvotes: 2
Reputation: 700
You could do in this way, my example have the async flavor, but the the concept is the same
public async Task<JsonResult> GetTareasAsync(int proyectoId)
{
ICollection<Tarea> x = await GetTareasInnerAsync(proyectoId).ConfigureAwait(false);
return Json(x, new Newtonsoft.Json.JsonSerializerSettings() { MaxDepth = 1 });
}
Upvotes: 0