Introduction
While generating JSON in ASP.NET MVC project, I found out the generated JSON responses are actually not in camel case format. Plus:
- JSON not indented
- Exception while serializing the single
null
value - Exception with reference loop properties
Today, I am going to share how to use Newtonsoft.Json and configure JSON serialization settings in different types of projects.
JSON Example
MVC
Using a custom JsonResult
class for camel case JSON:
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonCamelCaseResult : JsonResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
private const string HttpMethod = "GET";
private const string DefaultContentType = "application/json";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod,
HttpMethod, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("HttpMethod 'GET' is not allowed");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(ContentType) ? DefaultContentType : ContentType;
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
}
}
JSON helper class:
public class CamelJsonHelper
{
public JsonCamelCaseResult Json(object data)
{
return new JsonCamelCaseResult
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
add a new method to the Controller
or BaseController
to use this helper class:
public JsonResult JsonCamel(object value)
{
return new CamelJsonHelper().Json(value);
}
For MVC projects, there is no global setting option.
Web Form
Add serialization setting at Global.asax.cs.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
now serializing object like:
string json = JsonConvert.SerializeObject(DataProvider.Hierarchy())
This is also applicable for Aspx, Razor & C# !!!
If we don't want to configure it globally, we can do:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
var data = DataProvider.Hierarchy();
string json = JsonConvert.SerializeObject(data, settings);
Web API
Add new config class to App_Start:
public class ResponseSerializerConfig
{
public static void Register(HttpConfiguration configuration)
{
JsonResponse(configuration);
XmlResponse(configuration);
}
private static void XmlResponse(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
private static void JsonResponse(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
}
}
Apply this config class at Global.asax.cs.
ResponseSerializerConfig.Register(GlobalConfiguration.Configuration);
Addition Settings
Enum
{"Enum":"Hello"}
rather than {"Enum":0}
Converters = new List<JsonConverter> { new StringEnumConverter() }
Reference Loop
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
References $id/$ref
PreserveReferencesHandling = PreserveReferencesHandling.All;
To manage $id
/$ref
at js client, please do check:
TimeZone & DateTime
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DateFormatHandling = DateFormatHandling.IsoDateFormat
This post will help you to quick start projects will minimal JSON serializer settings. Please do check the attached VS2017 example project.