Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

camelCase JSON Response in ASP.NET Projects

0.00/5 (No votes)
8 Feb 2019 2  
Configure JSON serialization settings

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    /*prevent $id/$ref 
                                                                              at client end*/
        };

        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:

/*hide base*/
//public new JsonResult Json(object value)
//{
//    return new CamelJsonHelper().Json(value);
//}

/*new method*/
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.

/*comment and see the regular serialization*/
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Formatting = Formatting.Indented,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    PreserveReferencesHandling = PreserveReferencesHandling.None    /*prevent $id/$ref at client end*/
};

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    /*prevent $id/$ref at client end*/
};
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    /*prevent $id/$ref 
                                                                              at client end*/
        };
    }
}

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.Objects is more popular*/
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here