/questions/52797153/how-to-determine-if-a-json-object-contains-only-a-specific-key

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;

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/52797153/how-to-determine-if-a-json-object-contains-only-a-specific-key

    class TestClass
    {
        public static void Test()
        {
			int count = 0;

			var jObject = JObject.Parse(GetJson());
			
			foreach (var category in jObject["Categories"].OfType<JObject>())
			{
				var result = category.Count == 1 && category.Property("Name") != null;
								
				Console.WriteLine("Result for Category \"{0}\" = {1}:", category["Name"], result);
				Console.WriteLine("   " + category.ToString(Formatting.None));
				if (result)
					count++;
			}
			
			Assert.IsTrue(count == 4, string.Format("Wrong number of objects {0} selected!", count));
		}	
		
		static string GetJson()
		{
			var json = @"{
    ""Name"": ""ThirdParty"",
    ""Categories"": [
        { ""Name"": ""Identity"" },
        {
            ""Name"": ""Contact Information"",
            ""Mandatory"": true,
            ""Fields"": [
                { ""Name"": ""Phones"" },
                { ""Name"": ""Faxes"" },
                { ""Name"": ""Emails"" }
            ]
        },
        { ""Name"": ""Addresses"" },
        { ""Name"": ""Bank Accounts"" },
		{ },
        { ""No Name"": ""this object has no Name property and so should have been filtered out"" },
        { ""Name"": ""Test data"" },
    ]
}
";
			return json;
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

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