Search code examples
c#jsonjson.netjson-deserialization

How to Check if Json object has all values filled


I am getting a big nested json object from an external api. I want to make sure all fields are populated in that json object. Is there any libray available to do that? Newtonsoft.Json has JToken class which checks if the Json's schema is valid or not but i don't find any method to check if all the fields inside json object are filled.

Scenario : I am building an api which gathers information about a person or entity. there are numerous sources of information. I need to continue searching for the data until the required object is full. So first call goes to api1, gets some data, checks if object is full. If object is not full then goes to api2 and so on. So the call returns after the object is full. One key point is that the required object schema is not static.

I could deserialize it to a POCO and loop through each nested object but i am looking for a better solution.

Any suggestion is highly appreciated.


Solution

  • If you have a JSON string and simply want to check whether any property value or array item are null, you can parse to a JToken, recursively descend the JToken hierarchy with JContainer.DescendantsAndSelf(), and check each JValue for being null using the following extension method:

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

    And then do:

    var root = JToken.Parse(jsonString);
    var anyNull = root.AnyNull();
    

    If you just want to check for null property values (i.e. null values in an array are OK) you can use the following extension method:

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

    (It isn't entirely clear from your question which you want.)

    Sample .Net fiddle.