You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I made a custom serializer that will check for required properties when serializing from an object that uses the Required property of the JsonProperty attribute. I doubt if its something that you would want to include by default but I thought I'd throw it out there in case anybody else was looking some to do the same.
I guess it would add a bit of extra overhead to serializing, but it seems to work ok with no noticable impact on performance with the limited testing I've done so far.
publicclassJsonRequestBodyWithRequiredPropertiesSerializer:RequestBodySerializer{/// <summary>/// Gets or sets the serializer settings to pass to JsonConvert.SerializeObject/// </summary>publicJsonSerializerSettingsJsonSerializerSettings{get;set;}/// <inheritdoc/>publicoverrideHttpContentSerializeBody<T>(Tbody,RequestBodySerializerInfoinfo){if(EqualityComparer<T>.Default.Equals(body,default(T)))returnnull;varjsonSerializerSettings=JsonSerializerSettings??newJsonSerializerSettings(){ContractResolver=newDefaultContractResolver()};varcontract=(JsonObjectContract)jsonSerializerSettings.ContractResolver.ResolveContract(typeof(T));foreach(JsonPropertypropertyincontract.Properties){Required?propertyRequired=property.Required;RequiredresolvedRequired=property.Ignored?Required.Default:propertyRequired??contract.ItemRequired??Required.Default;if(resolvedRequired==Required.Always&&null==property.ValueProvider.GetValue(body)){thrownewJsonSerializationException($"Required property '{property.UnderlyingName}' is null.");}}varcontent=newStringContent(JsonConvert.SerializeObject(body,JsonSerializerSettings));content.Headers.ContentType.MediaType="application/json";returncontent;}}
The text was updated successfully, but these errors were encountered:
I made a custom serializer that will check for required properties when serializing from an object that uses the Required property of the JsonProperty attribute. I doubt if its something that you would want to include by default but I thought I'd throw it out there in case anybody else was looking some to do the same.
I guess it would add a bit of extra overhead to serializing, but it seems to work ok with no noticable impact on performance with the limited testing I've done so far.
The text was updated successfully, but these errors were encountered: