I am parsing a json reply, this reply can be different depending on if the call succeeded or not.
I created a function to check if the deserialization was sucessful, (return true + data or false + no-data)
static private bool TryParse<T>(string json, out T result)
{
try
{
result = Deserialize.FromJson<T>(json);
return true;
}
catch
{
result = default;
return false;
}
}
.
public class Success_type
{
[JsonProperty("success")]
public string Success { get; set; }
}
public class Failure_type
{
[JsonProperty("status")]
public bool Status { get; set; }
[JsonProperty("reason")]
public string Reason { get; set; }
}
public static class Deserialize
{
public static T FromJson<T>(string json) => (T)JsonConvert.DeserializeObject<T>(json, QuickType.Converter.Settings);
}
Example:
if (TryParse(json, out Success_type expected_success))
{
//do sosmething with expected_success
}
if (TryParse(json, out Failure_type expected_failure))
{
//do sosmething with expected_failure
}
i was expecting an exception to be thrown in DeserializeObject.FromJson<T>(json)
because json is not of type T. however, it succeeds, TryParse() returns true and just contains null items. why is that / how to i catch a mismatch?