2

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
    }
]}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Nowadays you don't need a custom contract resolver, try with snake case:

    var settings = new JsonSerializerSettings {
      ContractResolver = new DefaultContractResolver {
        NamingStrategy = new SnakeCaseNamingStrategy()
      }
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.