Recently, I implemented an application using C# related to a pet's social media platform. In this post, I'm going to discuss dealing with null values when calling JObject.Parse() and checking for empty or null JToken within a JObject. Let's get started.
Here you can see my code:
JArray clientList = (JArray)clientsParsed["feedObject"];

foreach (JObject item in clientList.Children())
{
    command.Parameters["@SqlParameter"].Value = ConvertFeedModelToSqlValue(item["KeyName"].ToObject<FeedModel>());
}

public static object ConvertFeedModelToSqlValue(FeedModel feedModel)
{
    if (feedModel != null)
        return (object)feedModel;
    else
        return (object)DBNull.Value;
}
To check for empty or null JToken in a JObject, you can use the following approach:
JArray clientList = (JArray)clientsParsed["feedObject"];

if (clientList != null && clientList.HasValues)
{
    foreach (JObject item in clientList.Children())
    {
        JToken keyNameToken = item["KeyName"];
        if (keyNameToken != null && !keyNameToken.IsNullOrEmpty())
        {
            command.Parameters["@SqlParameter"].Value = ConvertFeedModelToSqlValue(keyNameToken.ToObject<FeedModel>());
        }
        else
        {
            // Handle case where keyNameToken is null or empty
        }
    }
}
else
{
    // Handle case where clientList is null or empty
}


FeedModel is the class the structure of each item in the clientList, Instead of converting a JToken directly to a SQL value, we now convert a FeedModel object to a SQL value using The ConvertFeedModelToSqlValue method accepts a FeedModel object and checks if it's not null before returning it. If the FeedModel is null, it returns DBNull.Value.
Now lets improve that code

If you are working on a C# project and looking for ways to check for empty or null JToken within a JObject, you've come to the right place. In this post, we will discuss possible solutions. Specifically, we'll address how to handle null values when calling JObject.Parse. You can try the following approach:

Check if JToken is empty array

JObject response = JObject.Parse(responseString);
JToken data = response["value"];

if (data.Type == JTokenType.Array && ((JArray)data).Count == 0)
{
    // The data array is empty
    // Handle the empty array case here
}
else if (data == null)
{
    // The data token is null
    // Handle the null case here
}
else
{
    // The data token contains an array with elements
    // Handle the non-empty array case here
}
Above code checks if the data token is an array and then verifies if 's empty. Additionally, it checks if the data token is null to handle that case separately.
Alternatively, we can use LINQ operations to check if 'data' has any values
        if (data.Any())
        {
            Console.WriteLine("The 'data' token contains values.");
        }
        else
        {
            Console.WriteLine("The 'data' token is either null or empty.");
        }

The HasValues property of JToken returns true if the token contains child tokens. It provides a simple way to check whether a token has any values.
The Any() LINQ method checks if the sequence contains any elements.It's useful for situations where we want to check if a token contains any elements.
Both approaches are effective for checking if a JToken is null or empty, but they have slight differences in how they operate.The HasValues property directly checks whether the token has child tokens, while Any() iterates through the sequence to determine if there are any elements.


5 Ways Checking for empty or null JToken in a JObject in C#

Using IsNull Property:
if (jObject["propertyName"] == null || jObject["propertyName"].IsNull())
{
    // Handle null or empty case here
}
Using Type Property:

if (jObject["propertyName"] == null || jObject["propertyName"].Type == JTokenType.Null)
{
    // Handle null or empty case here
}
Using HasValues Property:

if (jObject["propertyName"] == null || !jObject["propertyName"].HasValues)
{
    // Handle null or empty case here
}
Using Value<T> Method (for value types):
if (jObject["propertyName"] == null || jObject["propertyName"].Value<int>() == 0)
{
    // Handle null or empty case here
}
public static class JTokenExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Null) ||
               (!token.HasValues);
    }
}

// Usage
if (jObject["propertyName"].IsNullOrEmpty())
{
    // Handle null or empty case here
}
let's create a JSON string representing a FeedModel and show you how to check it. Here's an example, Below code creates a sample FeedModel object, serializes it into a JSON string, and then parses that JSON string into a JObject. It then checks various properties within the FeedModel and prints messages based on their existence and validity.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

public class FeedModel
{
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime PublishedDate { get; set; }
    public int Likes { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Create a sample FeedModel object
        FeedModel feed = new FeedModel
        {
            Title = "Sample Title",
            Description = "This is a sample description.",
            PublishedDate = DateTime.Now,
            Likes = 10
        };

        // Serialize FeedModel object to JSON string
        string jsonString = JsonConvert.SerializeObject(feed);

        // Deserialize JSON string to JObject
        JObject jsonFeed = JObject.Parse(jsonString);

        // Check if Title property exists and is not null or empty
        if (jsonFeed["Title"] != null && !string.IsNullOrEmpty(jsonFeed["Title"].ToString()))
        {
            Console.WriteLine("Title: " + jsonFeed["Title"]);
        }
        else
        {
            Console.WriteLine("Title is missing or empty.");
        }

        // Check if Description property exists and is not null or empty
        if (jsonFeed["Description"] != null && !string.IsNullOrEmpty(jsonFeed["Description"].ToString()))
        {
            Console.WriteLine("Description: " + jsonFeed["Description"]);
        }
        else
        {
            Console.WriteLine("Description is missing or empty.");
        }

        // Check if PublishedDate property exists and is of type DateTime
        if (jsonFeed["PublishedDate"] != null && jsonFeed["PublishedDate"].Type == JTokenType.Date)
        {
            Console.WriteLine("Published Date: " + jsonFeed["PublishedDate"]);
        }
        else
        {
            Console.WriteLine("Published Date is missing or invalid.");
        }

        // Check if Likes property exists and is of type integer
        if (jsonFeed["Likes"] != null && jsonFeed["Likes"].Type == JTokenType.Integer)
        {
            Console.WriteLine("Likes: " + jsonFeed["Likes"]);
        }
        else
        {
            Console.WriteLine("Likes is missing or invalid.");
        }
    }
}