在从PascalCase(默认)到camel的下列JsonFormatter的ContractResolver配置之后,我在驼峰的情况下获得了以下Json输出。
但是,我更喜欢在小写和下划线中实现Json输出(大写应该用下划线替换)。有任何想法吗? :)
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;
}
类属性
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输出
"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
}
]}
首选输出
"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
}
]}
答案 0 :(得分:3)
您需要创建一个继承自DefaultContractResolver的自定义ContractResolver。见the Newtonsoft documentation。然后,您可以循环遍历属性名称中的字符,并根据需要插入下划线/使字符小写。