1

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?

kei
  • 159
  • 9
  • 1
    Add a JsonSerializerSettings where you specify `[Settings].MissingMemberHandling = MissingMemberHandling.Error` or add `Required = Required.Always` as a parameter of a `[JsonProperty]`. You already have `QuickType.Converter.Settings`, modify what's in there. The default result is ignoring the missing members and initializes to default values (unless otherwise specified) the members of the class type that is representing ``. – Jimi Nov 14 '19 at 02:55
  • this is exactly what i was looking for, if you post as an answer ill accept it – kei Nov 14 '19 at 04:13
  • 1
    So, duplicate of [Detect if deserialized object is missing a field with the JsonConvert class in Json.NET](https://stackoverflow.com/a/21032130/3744182) and/or [Json.NET require all properties on deserialization](https://stackoverflow.com/a/29660550/3744182)? – dbc Nov 14 '19 at 18:07

0 Answers0