如何省略get-only属性,只有当[JsonProperty]属性没有设置在它
本文关键字:属性 设置 JsonProperty get-only 何省略 | 更新日期: 2023-09-27 18:06:37
我使用Json。Net在我的项目中。我需要找到一个解决方案,只有当属性[JsonProperty]
未设置时,才能获得仅属性不序列化。
public class Example
{
[JsonProperty]
public string ThisPropertyHasToBeSerialized {get;}
public string ThisPropertyHasToBeSkipped {get;}
}
我找到了它的部分答案:是否有一种方法可以忽略Json中的get-only属性?. NET不使用JsonIgnore属性?但是我想留下一个机会,以便在需要时序列化仅获取属性。我正在考虑实现它在CreateProperty函数像这样
public class CustomContractResolver : DefaultContractResolver
{
public static readonly CustomContractResolver Instance = new CustomContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if(property.Writable||????????????)return property;
else ?????
}
}
是否有办法检查json属性是否设置在属性([JsonProperty]
)上,而不是[JsonIgnore]
?谢谢。
你可以这样实现你的解析器:
public class CustomContractResolver : DefaultContractResolver
{
public static readonly CustomContractResolver Instance = new CustomContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
// Ignore get-only properties that do not have a [JsonProperty] attribute
if (!property.Writable && member.GetCustomAttribute<JsonPropertyAttribute>() == null)
property.Ignored = true;
return property;
}
}
小提琴:https://dotnetfiddle.net/4oi04N