CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/74995241/asp-net-core-system-text-json-how-to-reject-unknown-properties-in-payload
#nullable enable
public static class JsonExtensions
{
public static DefaultJsonTypeInfoResolver AddMissingMemberHandlingError(this DefaultJsonTypeInfoResolver resolver)
{
resolver.Modifiers.Add(typeInfo =>
{
if (typeInfo.Kind != JsonTypeInfoKind.Object)
return;
if (typeInfo.Properties.Any(p => p.IsExtensionData))
return;
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;
if (dictionary != null)
throw new JsonException();
};
typeInfo.Properties.Add(property);
});
return resolver;
}
}
public class Model
{
public string? Value { get; set; }
public Inner Inner { get; set; } = new ();
}
public class Inner
{
[JsonExtensionData]
public Dictionary<string, object>? ExtensionData { get; set; }
}
class TestClass
{
public static void Test()
{
foreach (var json in GetBadJson())
{
TestBadJson(json);
}
foreach (var json in GetGoodJson())
{
TestGoodJson(json);
}
}
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 []
{
"""
{
"Value" : "some Value",
"Inner" :
{
"foo" : "bar"
},
"Unknown" : 111
}
"""
};
static IEnumerable<string> GetGoodJson() => new []
{
"""
{
"Value" : "some Value",
"Inner" :
{
"foo" : "bar"
}
}
""",
"""
{
"Value" : "some Value",
"Inner" :
{
}
}
"""
};
}
public class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}