When deserializing a JSON object with nested objects, with a required property on one of the nested objects, Deserialize does not throw an Exception. But if I add the JsonProperty.Required decoration to the base object, it does (as I'd expect). This happens when the input string is the entirely wrong type, but is properly formatted JSON.
So, the problematic input is "{\"Errors\":[\"This is an error\"]}" (which is the response from a webservice, either it's an array of error messages like this, or it's a properly serialized UserInformationRequest). Code to clarify:
Base Object JsonProperty functioning properly:
public class UserInformation
{
public string ID;
...
public string LoginName;
...
}
public class UserInformationRequest
{
[JsonProperty(Required = Required.Always)]
public string TimeStamp;
public UserInformation User;
}
...
public static UserInformationRequest GetUserInformationRequestFromString(string userInformation)
{
try
{
return JsonConvert.DeserializeObject<UserRequestInformation>(userInformation);
}
catch (Exception ex)
{
//exception thrown when userInformation.TimeStamp is null, as expected
return null;
}
}
Nested JsonProperty not functioning properly:
public class UserInformation
{
public string ID;
...
[JsonProperty(Required = Required.Always)]
public string LoginName;
...
}
public class UserInformationRequest
{
public string TimeStamp;
public UserInformation User;
}
...
public static UserInformationRequest GetUserInformationRequestFromString(string userInformation)
{
try
{
return JsonConvert.DeserializeObject<UserRequestInformation>(userInformation);
}
catch (Exception ex)
{
//never gets here - no exception thrown if userInformation.User.LoginName is null
return null;
}
}
Given this, when attempting to deserialize the Errors array into the UserInformationRequest, an exception is properly thrown if there is a JsonProperty on the base object, but it is never thrown if the nested object contains a JsonProperty.
Working dotnetfiddles demonstrating the issue: JsonProperty on base object: https://dotnetfiddle.net/qvyPfP JsonProperty on nested object: https://dotnetfiddle.net/M3F0rb