https://stackoverflow.com/questions/78185962/net-json-property-custom-required-logic

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/78185962/net-json-property-custom-required-logic

	public class Foo
	{
		[JsonConstructor]
		// Make public if you want to enforce the same requirements during regular construction
		protected Foo(int number, string text) 
		{
			if (number > 10 && text == null)
				throw new ArgumentException("missing text");
			this.Number = number;
			this.Text = text;
		}
		
		// Remove if you want to enforce the same requirements during regular construction
		public Foo() { }
		
		[JsonProperty(Required = Required.Always)]
		public int Number { get; set; }

		public string Text { get; set; }
	}

    class TestClass
    {
        public static void Test()
        {
			Assert.DoesNotThrow(() => JsonConvert.DeserializeObject<Foo>("""{ "Number": 5 }"""));
			Assert.That(() => JsonConvert.DeserializeObject<Foo>("""{ "Number": 20 }"""), Throws.Exception);
			Assert.DoesNotThrow(() => JsonConvert.DeserializeObject<Foo>("""{ "Number": 20, "Text": "Bar" }"""));
			Assert.That(() => JsonConvert.DeserializeObject<Foo>("""{ "Number": 20, "Text" : null }"""), Throws.Exception);
		}	
	}

	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("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;