Home > Mobile >  ASP.NET Core and Newtonsoft JSON.NET : how to force to fail on invalid fields?
ASP.NET Core and Newtonsoft JSON.NET : how to force to fail on invalid fields?

Time:06-08

We have a .NET Core 3.1 web app and use Newtonsoft JSON.NET serializer there registered for serializing/deserializing. But now we got stupid client who send us invalid JSON which contain fields which we don't have in our models. It's normal for JSON to ignore them, but I need to find way to create model state errors when deserializer finds invalid fields.

We have problem with optional fields so default validation won't help here.

CodePudding user response:

based on this doc try something like this

Class c = JsonConvert.DeserializeObject<List<Class>>("your string",
    new JsonSerializerSettings
    {
        Error = delegate(object sender, ErrorEventArgs args)
        {
            errors.Add(args.ErrorContext.Error.Message);
            args.ErrorContext.Handled = true;
        },
        Converters = { new IsoDateTimeConverter() }
    });

error handler: args.ErrorContext.Handled = {true/false};

CodePudding user response:

found solution

SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;

will throw error when my model doens't have fields from json. Bad naming I was thinking that it'll work vice versa.

  • Related