1

I have a simple class I want to deserialize a json string into :

public class ConnectClientResponse
{
    public bool result { get; set; }
}

Call of the Deserialize method :

try
{
    var response = JsonConvert.DeserializeObject<ConnectClientResponse>(jsonString);
}
catch (JsonSerializationException)
{
    // Exception should be thrown
}

The issue is when the json string has the same form as the ConnectClientResponse class but the property name is not the same, no exception is thrown.

Is this a normal behaviour ? If so, how can I check if the properties names are the same ?

Exemple of invalid json, the property name doesn't match the ConnectClientResponse "result" property name :

{
    "test" : true
}
Valsov
  • 27
  • 6
  • 1
    Of course they have to be the same how else would they map? You can create a custom converter and perform your checks there. – Ric Feb 19 '18 at 19:07
  • This is intended behavior, Json.NET will ignore unknown JSON properties. See [Can you detect if an object you deserialized was missing a field with the JsonConvert class in Json.NET](https://stackoverflow.com/q/21030712) if you don't want that. Alternatively, if you want to make any or all c# properties as required, see [Json.NET require all properties on deserialization](https://stackoverflow.com/q/29655502). – dbc Feb 19 '18 at 19:07

2 Answers2

2

Your actual problem is not that there's a "similar" property, but that your property isn't mandatory.

If you want certain properties to be mandatory, mark it with the JsonProperty attribute, e.g. [JsonProperty(Required = Required.Always)]. You can also use the value Required.AllowNull instead, if null values should be valid, as long as the property name is there.

Wormbo
  • 4,978
  • 2
  • 21
  • 41
  • What is the best practice between [JsonProperty(Required = Required.Always)] and using the MissingMemberHandling ? I tested both of them and they solved my problem. – Valsov Feb 19 '18 at 19:18
  • 2
    @Valsov - they do different, complementary things. `MissingMemberHandling` throws an exception on an extra, unknown property in the JSON. `Required = Required.Always` throws an exception in a missing property in the JSON. In your JSON you have both problems. – dbc Feb 19 '18 at 19:36
1

You can use the MissingMemberHandling on JsonSerializerSettings to control this behaviour. https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_MissingMemberHandling.htm

driis
  • 161,458
  • 45
  • 265
  • 341