Click here to Skip to main content
15,883,705 members
Articles / Web Development / ASP.NET
Tip/Trick

camelCase JSON Response in ASP.NET Projects

Rate me:
Please Sign up or sign in to vote.
4.89/5 (2 votes)
8 Feb 2019CPOL1 min read 14.7K   60   1  
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

Image 1

Image 2

MVC

Using a custom JsonResult class for camel case JSON:

C#
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
C#
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:

C#
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:

C#
/*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.

C#
/*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:

C#
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:

C#
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:

C#
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.

C#
ResponseSerializerConfig.Register(GlobalConfiguration.Configuration);

Addition Settings

Enum

{"Enum":"Hello"} rather than {"Enum":0}

C#
Converters = new List<JsonConverter> { new StringEnumConverter() }

Reference Loop

C#
ReferenceLoopHandling = ReferenceLoopHandling.Serialize

References $id/$ref

C#
/*PreserveReferencesHandling.Objects is more popular*/
PreserveReferencesHandling = PreserveReferencesHandling.All;

To manage $id/$ref at js client, please do check:

TimeZone & DateTime

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --