本文主要是介绍JsonSerializerSettings 转小写 指定层级,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在.NET Core中,如果你想要在序列化JSON时将特定层级的属性名转换为小写,你可以使用Newtonsoft.Json
库的自定义ContractResolver
。以下是一个简单的例子,演示如何只转换第一层级的属性名为小写:
var json = await _energyQualityDataService.GetTableAsync(query);var settings = new JsonSerializerSettings{ContractResolver = new LowercasePropertyNamesContractResolver()};return Json(json, settings);
public class LowercasePropertyNamesContractResolver : DefaultContractResolver{protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization){JsonProperty property = base.CreateProperty(member, memberSerialization);// 转换指定层级的数据变为小写if (property.DeclaringType.Name.Contains("ServiceResponse")){property.PropertyName = property.PropertyName.ToLowerInvariant();}if (property.DeclaringType == typeof(PagedResult<DataTable>)){property.PropertyName = property.PropertyName.ToLowerInvariant();}return property;}}
这篇关于JsonSerializerSettings 转小写 指定层级的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!