using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static partial class JsonExtensions
public static bool AnyNull(this JToken rootNode)
return rootNode.DescendantsAndSelf()
.Any(n => n.Type == JTokenType.Null);
public static IEnumerable<JToken> DescendantsAndSelf(this JToken rootNode)
return Enumerable.Empty<JToken>();
var container = rootNode as JContainer;
return container.DescendantsAndSelf();
return new[] { rootNode };
public static partial class JsonExtensions
public static bool AnyNullPropertyValues(this JToken rootNode)
return rootNode.DescendantsAndSelf()
.Any(p => p.Value == null || p.Value.Type == JTokenType.Null);
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()
""PrimaryEmail"": ""A@1"",
""CellPhoneNumber"": null,
""OrganizationUnit"": null,
""Keywords"" : [""hello"", null]
""NextPage"": ""NextPage""
static string GetNonNullJson()
""PrimaryEmail"": ""A@1"",
""CellPhoneNumber"": """",
""OrganizationUnit"": """",
""Keywords"" : [""hello"", """"]
""NextPage"": ""NextPage""
static string GetJsonWithNullOnlyInArray()
""PrimaryEmail"": ""A@1"",
""CellPhoneNumber"": """",
""OrganizationUnit"": """",
""Keywords"" : [""hello"", null]
""NextPage"": ""NextPage""
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");