[程式開發技巧,] ASP.NET Core 動態忽略JSON物件屬性 | JSON.NET
這篇簡單分享在JSON轉換中
如何動態忽略物件的屬性
[ Resolver類別 ]
public class IgnorePeopertiesResolver : CamelCasePropertyNamesContractResolver
{
public static List<string> PropertyNames { get; } = new List<string>();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty p = base.CreateProperty(member, memberSerialization);
foreach (string name in PropertyNames)
{
if (p.PropertyName.ToLower() == name.ToLower())
{
p.Ignored = true;
}
}
return p;
}
}
[ Extension類別 ]
public static class JsonIgnorePropertyExtension
{
public static void AddIgnoreProperties<T>(this T[] arr, Func<T, string[]> callback)
{
IgnorePeopertiesResolver.PropertyNames.Clear();
if (arr.Length > 0)
{
IgnorePeopertiesResolver.PropertyNames.AddRange(callback(arr[0]));
}
}
public static void AddIgnoreProperties<T>(this T obj, params string[] names)
{
IgnorePeopertiesResolver.PropertyNames.Clear();
IgnorePeopertiesResolver.PropertyNames.AddRange(names);
}
}
[ Services DI ]
services.AddControllers().AddNewtonsoftJson(setup =>
{
setup.SerializerSettings.ContractResolver = new IgnorePeopertiesResolver();
});
[ 使用示範 ]
someArray.AddIgnoreProperties(data => { return new string[] { nameof(data.Account) }; });
return Ok(someArray);
someObject.AddIgnoreProperties(nameof(someObject.Password));
return Ok(someObject);
主要是透過static與extension完成整個流程
在回傳ActionResult之前呼叫AddIgnoreProperties方法
JSON在序列化時就會判斷哪些屬性名稱是要忽略的
留言