Search code examples
jsonrestasp.net-web-apijson.netasp.net-web-api2

Web API 2 Json Output in Lower Case and Underscore


After the following JsonFormatter's ContractResolver configuration from PascalCase (default) to camel case, am getting the following Json Output in camel case.

But, I prefer to achieve the Json output in Lower Case along with underscore (the uppercase should be replaced with underscore). Any ideas? :)

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);

    EnableCamelCase();
}

private void EnableCamelCase()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}

Class Properties

public int MenuId { get; set; }
public byte TypeId { get; set; }
public string MenuName { get; set; }
public string Description { get; set; }
public string Tooltip { get; set; }
public byte? Minimum { get; set; }
public byte? Maximum { get; set; }
public bool CanMultiSelect { get; set; }
public byte SortOrder { get; set; }

Camel Case Json Output

"items": [
    {
      "menuId": 82,
      "typeId": 1,
      "menuName": "dsf",
      "description": "sdafsdafsd",
      "tooltip": null,
      "minimum": null,
      "maximum": null,
      "canMultiSelect": false,
      "sortOrder": 0
    },
    {
      "menuId": 83,
      "typeId": 1,
      "menuName": "sdfad",
      "description": "fsdfda",
      "tooltip": null,
      "minimum": null,
      "maximum": null,
      "canMultiSelect": false,
      "sortOrder": 0
    }
]}

Preferred Output

"items": [
    {
      "menu_id": 82,
      "type_id": 1,
      "menu_name": "dsf",
      "description": "sdafsdafsd",
      "tooltip": null,
      "minimum": null,
      "maximum": null,
      "can_multi_select": false,
      "sort_order": 0
    },
    {
      "menu_id": 82,
      "type_id": 1,
      "menu_name": "dsf",
      "description": "sdafsdafsd",
      "tooltip": null,
      "minimum": null,
      "maximum": null,
      "can_multi_select": false,
      "sort_order": 0
    }
]}

Solution

  • You'll need to create a custom ContractResolver that inherits from DefaultContractResolver. See the Newtonsoft documentation. You can then loop round the characters in the property name and insert the underscore/ make the character lowercase as appropriate.