I use Json.Net in my project. I need to find a solution where get-only properties do not serialize only if attribute [JsonProperty]
is not set.
public class Example
{
[JsonProperty]
public string ThisPropertyHasToBeSerialized {get;}
public string ThisPropertyHasToBeSkipped {get;}
}
I found a partial answer to it at: Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes? But I want to leave an opportunity for get-only properties to be serialized in case it is needed. I am thinking of implementing it in CreateProperty function like this
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 ?????
}
}
Is there a way to check if json Attribute was set on a property ( [JsonProperty]
) but not [JsonIgnore]
? Thanks.
You can implement your resolver like this:
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;
}
}
Fiddle: https://dotnetfiddle.net/4oi04N
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.