1

I have a class I want to deserialize into using Json.NET:

public class Settings {
    public MoreSettings More { get; set; }
}

public class MoreSettings {
    public int Value { get; set; }
}

I want the following examples without unknown properties to successfully deserialize.

1.1

{}

1.2

{
    "MoreSettings": null
}

1.3

{
    "MoreSettings": {
    }
}

1.4

{
    "MoreSettings": {
        "Value": 42
    }
}

I want the following examples with unknown properties to fail deserialization.

2.1

{
    "MoreSetting": null
}

2.2

{
    "MoreSettings": {
        "Values": 42
    }
}

I don't think I can use MissingMemberHandling since it will fail on missing values. I only want to fail on unknown values. Alternatives?

Linus
  • 3,254
  • 4
  • 22
  • 36
  • `MissingMemberHandling` does do what you want, 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/3744182) and https://dotnetfiddle.net/9u8Aa0. The real problem seems to be that, in `Settings`, you need to rename `More` to `MoreSettings`: `public class Settings { public MoreSettings MoreSettings { get; set; } }`. because currently neither `"MoreSettings"` nor `"MoreSetting"` exist in `Settings`. – dbc Dec 06 '18 at 17:39
  • Conversely if you want to fail on missing values in the JSON you would use `Required.Always`, see [Json.NET require all properties on deserialization](https://stackoverflow.com/q/29655502/3744182). – dbc Dec 06 '18 at 17:41

1 Answers1

1

You can set JsonSerializerSettings.MissingMemberHandling to MissingMemberHandling.Error to raise an error a property is found in the json, but not in your model. You can even add a handler to JsonSerializerSettings.Error to intercept the error.

public static void InitializeJsonSerializer()
{
    JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
    {
        MissingMemberHandling = MissingMemberHandling.Error,
        Error = ErrorHandler,
    };

    void ErrorHandler(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
    {
        if (e.ErrorContext.Error.Message.StartsWith("Could not find member "))
        {
            // do something...

            // hide the error
            e.ErrorContext.Handled = true;
        }
    }
}
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44