1 回答
TA贡献1963条经验 获得超6个赞
您可以使用自定义ContractResolver
来执行您想要的操作:
class NonNullablePropertiesRequiredResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
Type propType = prop.PropertyType;
if (propType.IsValueType && !(propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
prop.Required = Required.Always;
}
return prop;
}
}
反序列化时将解析器应用到您的应用程序中JsonSerializerSettings,如下所示:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new NonNullablePropertiesRequiredResolver();
MyParameters parms = JsonConvert.DeserializeObject<MyParameters>(json, settings);
工作演示: https: //dotnetfiddle.net/t56U2a
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报