Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonRequestBodySerializer with Required Properties check #68

Closed
netclectic opened this issue Sep 7, 2017 · 1 comment
Closed

JsonRequestBodySerializer with Required Properties check #68

netclectic opened this issue Sep 7, 2017 · 1 comment

Comments

@netclectic
Copy link

netclectic commented Sep 7, 2017

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.

public class JsonRequestBodyWithRequiredPropertiesSerializer : RequestBodySerializer
    {
        /// <summary>
        /// Gets or sets the serializer settings to pass to JsonConvert.SerializeObject
        /// </summary>
        public JsonSerializerSettings JsonSerializerSettings { get; set; }

        /// <inheritdoc/>
        public override HttpContent SerializeBody<T>(T body, RequestBodySerializerInfo info)
        {
            if (EqualityComparer<T>.Default.Equals(body, default(T)))
                return null;

            var jsonSerializerSettings = JsonSerializerSettings ?? new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() };
            var contract = (JsonObjectContract)jsonSerializerSettings.ContractResolver.ResolveContract(typeof(T));
            foreach (JsonProperty property in contract.Properties)
            {
                Required? propertyRequired = property.Required;
                Required resolvedRequired = property.Ignored ? Required.Default : propertyRequired ?? contract.ItemRequired ?? Required.Default;
                if (resolvedRequired == Required.Always && null == property.ValueProvider.GetValue(body))
                {
                    throw new JsonSerializationException($"Required property '{property.UnderlyingName}' is null.");
                }
            }

            var content = new StringContent(JsonConvert.SerializeObject(body, JsonSerializerSettings));
            content.Headers.ContentType.MediaType = "application/json";
            return content;
        }
    }
@canton7
Copy link
Owner

canton7 commented Sep 7, 2017

Thanks! I'll stick it in the FAQ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants