questions/46854592/how-to-check-if-json-object-has-all-values-filled

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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

    // https://stackoverflow.com/questions/46854592/how-to-check-if-json-object-has-all-values-filled?noredirect=1#46854592

    public static partial class JsonExtensions
    {
        public static bool AnyNull(this JToken rootNode)
        {
            if (rootNode == null)
                return true;
            // You might consider using some of the other checks from JsonExtensions.IsNullOrEmpty()
            // from https://stackoverflow.com/questions/24066400/checking-for-empty-null-jtoken-in-a-jobject
            return rootNode.DescendantsAndSelf()
                .OfType<JValue>()
                .Any(n => n.Type == JTokenType.Null);
        }

        public static IEnumerable<JToken> DescendantsAndSelf(this JToken rootNode)
        {
            if (rootNode == null)
                return Enumerable.Empty<JToken>();
            var container = rootNode as JContainer;
            if (container != null)
                return container.DescendantsAndSelf();
            else
                return new[] { rootNode };
        }
    }


    public static partial class JsonExtensions
    {
        public static bool AnyNullPropertyValues(this JToken rootNode)
        {
            if (rootNode == null)
                return true;
            return rootNode.DescendantsAndSelf()
                .OfType<JProperty>()
                .Any(p => p.Value == null || p.Value.Type == JTokenType.Null);
        }
    }

    class TestClass
    {
        public static void Test()
        {
            Test(GetNullJson(), true, true);
            Test(GetNonNullJson(), false, false);
            Test(GetJsonWithNullOnlyInArray(), true, false);

            Console.WriteLine("\nDone");
        }

        static void Test(string jsonString, bool shouldHaveAnyNull, bool shouldHaveAnyNullPropertyValues)
        {
            Console.WriteLine("\nInput JSON: ");
            Console.WriteLine(jsonString);

            var root = JToken.Parse(jsonString);
            var anyNull = root.AnyNull();
            var anyNullInProperties = root.AnyNullPropertyValues();
            Console.WriteLine("Nulls present at all: {0}; in property values: {1}.", anyNull, anyNullInProperties);

            Assert.IsTrue(anyNull == shouldHaveAnyNull);
            Assert.IsTrue(anyNullInProperties == shouldHaveAnyNullPropertyValues);
        }

        static string GetNullJson()
        {
            var json = @"{
  ""Items"": [[
    {
      ""FirstName"": ""A"",
      ""LastName"": ""A"",
      ""MiddleName"": """",
      ""PrimaryEmail"": ""A@1"",
      ""Active"": true,
      ""CellPhoneNumber"": null,
      ""OrganizationUnit"": null,
      ""ID"": null,
      ""URI"": null,
      ""Keywords"" : [""hello"", null]
    }
  ]],
  ""NextPage"": ""NextPage""
}";
            return json;
        }

        static string GetNonNullJson()
        {
            var json = @"{
  ""Items"": [[
    {
      ""FirstName"": ""A"",
      ""LastName"": ""A"",
      ""MiddleName"": """",
      ""PrimaryEmail"": ""A@1"",
      ""Active"": true,
      ""CellPhoneNumber"": """",
      ""OrganizationUnit"": """",
      ""ID"": """",
      ""URI"": """",
      ""Keywords"" : [""hello"", """"]
    }
  ]],
  ""NextPage"": ""NextPage""
}";
            return json;
        }

        static string GetJsonWithNullOnlyInArray()
        {
            var json = @"{
  ""Items"": [[
    {
      ""FirstName"": ""A"",
      ""LastName"": ""A"",
      ""MiddleName"": """",
      ""PrimaryEmail"": ""A@1"",
      ""Active"": true,
      ""CellPhoneNumber"": """",
      ""OrganizationUnit"": """",
      ""ID"": """",
      ""URI"": """",
      ""Keywords"" : [""hello"", null]
    }
  ]],
  ""NextPage"": ""NextPage""
}";
            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;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
;