using System.Collections;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
public static class JsonExtensions
public static DefaultJsonTypeInfoResolver AddMissingMemberHandlingError(this DefaultJsonTypeInfoResolver resolver)
resolver.Modifiers.Add(typeInfo =>
if (typeInfo.Kind != JsonTypeInfoKind.Object)
if (typeInfo.Properties.Any(p => p.IsExtensionData))
var property = typeInfo.CreateJsonPropertyInfo(typeof(Dictionary<string, JsonElement>), "<>ExtensionData");
property.IsExtensionData = true;
property.Get = static (obj) => null;
property.Set = static (obj, val) =>
var dictionary = (Dictionary<string, JsonElement>?)val;
throw new JsonException();
typeInfo.Properties.Add(property);
public string? Value { get; set; }
public Inner Inner { get; set; } = new ();
public Dictionary<string, object>? ExtensionData { get; set; }
public static void Test()
foreach (var json in GetBadJson())
foreach (var json in GetGoodJson())
static void TestGoodJson(string json)
var options = new JsonSerializerOptions
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
.AddMissingMemberHandlingError(),
Assert.DoesNotThrow(() => JsonSerializer.Deserialize<Model>(json, options));
static void TestBadJson(string json)
var options = new JsonSerializerOptions
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
.AddMissingMemberHandlingError(),
var ex = Assert.Throws(Is.InstanceOf(typeof(JsonException)), () => JsonSerializer.Deserialize<Model>(json, options));
Console.WriteLine("Caught expected exception:\n{0}", ex);
static IEnumerable<string> GetBadJson() => new []
static IEnumerable<string> GetGoodJson() => new []
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");