[Fork] [Fork] [Fork] 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
	{
		[JsonProperty(Required = Required.Always)]
		public int Number { get; set; }

		string text;
		bool textSpecified;
		public string Text { get => text; set { text = value; textSpecified = true; } }
		
		[System.Runtime.Serialization.OnDeserialized]
		void OnDeserializedMethod(System.Runtime.Serialization.StreamingContext context)
		{
			if (Number > 10 && !textSpecified)
			{
				throw new JsonSerializationException("missing text");
			}
		}
	}

    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.DoesNotThrow(() => JsonConvert.DeserializeObject<Foo>("""{ "Number": 20, "Text" : null }"""));
		}	
	}

	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;
			}
		}
	}
;