Json.NET
Newtonsoft
JsonConvert
deserialization
missing field detection

Detect if deserialized object is missing a field with the JsonConvert class in Json.NET Newtonsoft

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To detect missing fields during JSON deserialization with Newtonsoft Json.NET, set MissingMemberHandling.Error in JsonSerializerSettings to throw when the JSON contains fields not in your class, or use [JsonProperty(Required = Required.Always)] to throw when your class expects a field that is missing from the JSON. You can also use JsonSerializer error handling events to log missing fields without throwing. These mechanisms ensure data integrity by catching schema mismatches early.

Detect Missing Fields in JSON (Required Properties)

When your C# class requires a field but the JSON does not include it:

csharp
1using Newtonsoft.Json;
2
3public class User
4{
5    [JsonProperty(Required = Required.Always)]
6    public string Name { get; set; }
7
8    [JsonProperty(Required = Required.Always)]
9    public string Email { get; set; }
10
11    [JsonProperty(Required = Required.Default)]  // Optional
12    public int? Age { get; set; }
13}
14
15// JSON missing the "Email" field
16string json = @"{ ""Name"": ""Alice"" }";
17
18// Throws JsonSerializationException: Required property 'Email' not found in JSON
19var user = JsonConvert.DeserializeObject<User>(json);

Required Attribute Options

csharp
1public class Config
2{
3    // Must be present and non-null
4    [JsonProperty(Required = Required.Always)]
5    public string ApiKey { get; set; }
6
7    // Must be present (can be null)
8    [JsonProperty(Required = Required.AllowNull)]
9    public string Description { get; set; }
10
11    // Default: no validation
12    [JsonProperty(Required = Required.Default)]
13    public int Timeout { get; set; }
14
15    // Must NOT be present (rare, for schema enforcement)
16    [JsonProperty(Required = Required.DisallowNull)]
17    public string InternalId { get; set; }
18}
19
20// Required.Always: missing or null → error
21// Required.AllowNull: missing → error, null → ok
22// Required.Default: missing → use default value, no error
23// Required.DisallowNull: present and null → error

Detect Extra Fields in JSON (MissingMemberHandling)

When the JSON contains fields not in your C# class:

csharp
1public class Product
2{
3    public string Name { get; set; }
4    public decimal Price { get; set; }
5}
6
7// JSON has an extra "discount" field not in Product class
8string json = @"{ ""Name"": ""Widget"", ""Price"": 9.99, ""discount"": 0.1 }";
9
10var settings = new JsonSerializerSettings
11{
12    MissingMemberHandling = MissingMemberHandling.Error
13};
14
15// Throws JsonSerializationException: Could not find member 'discount' on object of type 'Product'
16var product = JsonConvert.DeserializeObject<Product>(json, settings);

By default, MissingMemberHandling is set to Ignore, meaning extra JSON fields are silently skipped.

Using Error Handling Events

Log missing fields without throwing:

csharp
1var settings = new JsonSerializerSettings
2{
3    MissingMemberHandling = MissingMemberHandling.Error,
4    Error = (sender, args) =>
5    {
6        Console.WriteLine($"JSON error: {args.ErrorContext.Error.Message}");
7        args.ErrorContext.Handled = true;  // Don't throw, just log
8    }
9};
10
11string json = @"{ ""Name"": ""Widget"", ""unknown_field"": 42 }";
12var product = JsonConvert.DeserializeObject<Product>(json, settings);
13// Logs: "JSON error: Could not find member 'unknown_field' on object of type 'Product'"
14// product.Name = "Widget", deserialization continues

Attribute-Level Error Handling

csharp
1using Newtonsoft.Json;
2using Newtonsoft.Json.Serialization;
3
4[JsonObject(MissingMemberHandling = MissingMemberHandling.Error)]
5public class StrictConfig
6{
7    public string Host { get; set; }
8    public int Port { get; set; }
9}
10
11// Only StrictConfig enforces missing member detection
12// Other classes use the default (Ignore)

Validating After Deserialization

Check for null fields after deserialization:

csharp
1public class Order
2{
3    public string OrderId { get; set; }
4    public string CustomerId { get; set; }
5    public List<string> Items { get; set; }
6
7    public List<string> GetMissingFields()
8    {
9        var missing = new List<string>();
10        if (string.IsNullOrEmpty(OrderId)) missing.Add("OrderId");
11        if (string.IsNullOrEmpty(CustomerId)) missing.Add("CustomerId");
12        if (Items == null || Items.Count == 0) missing.Add("Items");
13        return missing;
14    }
15}
16
17string json = @"{ ""OrderId"": ""ORD-123"" }";
18var order = JsonConvert.DeserializeObject<Order>(json);
19
20var missing = order.GetMissingFields();
21if (missing.Any())
22{
23    Console.WriteLine($"Missing fields: {string.Join(", ", missing)}");
24}

Using JsonSchema Validation

For comprehensive schema validation:

csharp
1// Install: Install-Package Newtonsoft.Json.Schema
2using Newtonsoft.Json.Schema;
3using Newtonsoft.Json.Linq;
4
5string schemaJson = @"{
6    'type': 'object',
7    'required': ['name', 'email'],
8    'properties': {
9        'name': { 'type': 'string' },
10        'email': { 'type': 'string', 'format': 'email' },
11        'age': { 'type': 'integer' }
12    }
13}";
14
15var schema = JSchema.Parse(schemaJson);
16
17string json = @"{ ""name"": ""Alice"" }";
18JObject obj = JObject.Parse(json);
19
20bool isValid = obj.IsValid(schema, out IList<string> errors);
21// isValid = false
22// errors: "Required properties are missing from object: email."

Comparing with System.Text.Json

csharp
1// System.Text.Json (built-in .NET Core 3.0+)
2using System.Text.Json;
3using System.Text.Json.Serialization;
4
5public class User
6{
7    [JsonPropertyName("name")]
8    public string Name { get; set; }
9
10    // Required in .NET 7+
11    public required string Email { get; set; }
12}
13
14// System.Text.Json throws if 'required' keyword properties are missing (.NET 7+)
15var user = JsonSerializer.Deserialize<User>(json);

Common Pitfalls

  • Confusing MissingMemberHandling with Required: MissingMemberHandling.Error detects extra fields in JSON that are not in the C# class. Required.Always detects fields missing from JSON that are expected by the C# class. These solve opposite problems — use both for strict bi-directional validation.
  • Not handling JsonSerializationException: When Required.Always fails, it throws JsonSerializationException. If unhandled, this crashes the application. Wrap deserialization in try-catch and return meaningful error messages to the caller.
  • Using Required.Always on value types: A Required.Always on int Age throws when Age is missing from JSON. But int defaults to 0, which is a valid value. Use int? Age (nullable) with Required.AllowNull to distinguish between "missing" (null) and "present with value 0".
  • Global MissingMemberHandling.Error breaking polymorphic deserialization: If you set MissingMemberHandling.Error globally, JSON containing type discriminators or extra fields for derived types throws errors. Apply it per-class with [JsonObject(MissingMemberHandling = ...)] instead of globally.
  • Assuming default values mean the field was present: After deserialization, Age == 0 could mean the JSON had "Age": 0 or that Age was missing and defaulted. To distinguish, use int? Agenull means missing, 0 means explicitly set.

Summary

  • Use [JsonProperty(Required = Required.Always)] to ensure required JSON fields are present
  • Use MissingMemberHandling.Error in settings to detect unexpected extra fields in JSON
  • Use error handling events (settings.Error) to log issues without throwing exceptions
  • Combine Required attributes with nullable types (int?) to distinguish missing from default values
  • For comprehensive validation, use Newtonsoft.Json.Schema with a JSON Schema definition

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions