Fail the deserializatioin of JSON string if any expected properties don’t exist
Json.NET has another handy attribute, [JsonObject(ItemRequired = Required.Always)]. It makes every property of the class mandatory
[JsonObject(ItemRequired = Required.Always)]
public class UpdateWarrantyRequest
{
public int WarrantyYear { get; set; }
}
Then I can catch the exception and handle it.
public static class JsonExtensions
{
public static OperationResult<T> To<T>(this string payload)
{
try
{
return new OperationResult<T>(HttpStatusCode.OK,
JsonConvert.DeserializeObject<T>(payload));
}
catch (Exception)
{
var errorMessage = $"Failed in deserializing the payload:\n {payload}";
Console.WriteLine(errorMessage);
return new OperationResult<T>(HttpStatusCode.BadRequest, errorMessage);
}
}
}
Comments