When I have a straight forward object I can serialize using an ASP.NET MVC Controller like so:
public JsonResult Program(int id, int userId)
{
return Json(GetPrograms(userId).FirstOrDefault(f => f.Id == id), JsonRequestBehavior.AllowGet);
}
Client side, my response is a Javascript object:
Now I want my response JSON to have CamelCase property names like so:
So using JSON.NET and this SO answer I add this code to my ASP.NET MVC Controller:
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(program, serializerSettings);
So here is the problem, JsonConvert.SerializeObject
returns a JSON string, so when used here as a JsonResult:
public JsonResult Program(int id, int userId)
{
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(program, serializerSettings);
return Json(json, JsonRequestBehavior.AllowGet);
}
This really isn't a JsonResult like my first snippet of code in my question returns. It is a string response and I have to use Javascript JSON.parse
with a Web Client calling the Controller and handling the response.
Is there any way to CamelCase my properties and serialize a JSON object JsonResult?
I have tried JObject:
var serializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
JObject.FromObject(obj, serializer);
But that didn't work at all an my JsonResult is a bunch of empty Arrays: