In this article, we are going to learn different ways to get value by key from JObject in C#.

To download the source code for the video, visit our Patreon page (YouTube Patron tier).

Let’s start.


VIDEO: 4 Essential Ways to Get a Value from JObject.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!


What Is JObject?

JObject is a class type in the Json.NET library that represents a JSON object. The class provides methods that enable us to manipulate JSON data, like:

  • Creating JSON objects
  • Parsing JSON and reading data
  • Adding data to JSON objects

We won’t go deep into each of these use cases. Instead, we will only look at parsing JSON and reading data. We also covered how to iterate over a JSON array and how to deserialize JSON into a dynamic object using Json.Net.

Data Preparation

Our main focus for this article is learning how to read data from a JSON object using JObject. So let’s create a simple console application and install the Json.NET library using the command:

NuGet\Install-Package Newtonsoft.Json

After that, let’s add a new TestData class with a single method:

public string GenerateSingleJsonObject()
{
    const string car = $$"""
        {
            "name": "Charger",
            "make": "Dodge",
            "model": "RT",
            "year": 2019,
            "price": {
              "amount": 36100,
              "currency": "USD"
            } 
        }
        """ ;

    return car;
}

We have a method that returns a single JSON object as a string.

Now, let’s proceed to look at different ways how to get value by key from JObject in C# and process this JSON string. 

Different Ways to Get Value by Key From JObject

The Json.NET library provides us flexibility when reading values from a JSON object. We are going to look at four ways to do this:

  • Passing the key as an index
  • Using the JObject.Value<T>() method
  • Using the JObject.SelectToken() method
  • Using the JObject.TryGetValue() method

First, let’s add a new JObjectManipulation class, which we’ll use to illustrate these four approaches:

public class JObjectManipulation
{
    public string SingleJsonObject { get; set; }

    public JObjectManipulation()
    {
        InitializeData();
    }

    public void InitializeData()
    {
        var testData = new TestData();
        SingleJsonObject = testData.GenerateSingleJsonObject();
    }
}

In this class, we are initializing the SingleJsonObject class property in the InitializeData() method, which we then call in the constructor.

Passing the Key as an Index

In the JObjectManipulation class, let’s add a new method:

public int GetValuesUsingIndex()
{
    var jsonObject = JObject.Parse(SingleJsonObject);

    var name = (string)jsonObject["name"];
    var make = (string)jsonObject["make"];
    var model = (string)jsonObject["model"];
    var year = (int)jsonObject["year"];

    var price = (JObject)jsonObject["price"];
    var amount = (int)price["amount"];
    var currency = (string)price["currency"];

    Console.WriteLine($"A {make} {name} {model} {year} costs {amount} {currency} \n");

    return jsonObject.Count;
}

We first convert the SingleJsonObject string to a JObject using JObject.Parse. To get values from the JSON object, we pass the keys as indexes to the JObject, using the square bracket notation. After getting the values, we cast them to the desired type. 

The price key has nested JSON with amount and currency key-value pairs. To get these values, we follow the same steps, by first converting the value of price to a JObject using a cast:

var price = (JObject)jsonObject["price"]

Then, we access the values of amount and currency using the index of the resulting JObject:

var amount = (int)price["amount"];
var currency = (string)price["currency"];

If the JSON data is not deeply nested, we can use this method to get the values. However, if our JSON object has a deep hierarchy, accessing a value that is deep can be very tedious. That’s where the Value<T>() method comes into play.

Let’s tackle it next.

Using the Value<T>() Method

Using this method, we directly pass the key as the parameter to the method. In addition to that, we also pass the appropriate type as a type argument to the Value<T> method. The method then returns the value already cast.

That said, let’s create a new GetValuesUsingValueMethod method:

public int GetValuesUsingValueMethod()
{
    var jsonObject = JObject.Parse(SingleJsonObject);

    var name = jsonObject.Value<string>("name");
    var make = jsonObject.Value<string>("make");
    var model = jsonObject.Value<string>("model");
    var year = jsonObject.Value<string>("year");

    var amount = jsonObject.Value<JObject>("price")
       .Value<int>("amount");
    var currency = jsonObject.Value<JObject>("price")
       .Value<string>("currency");

    Console.WriteLine($"A {make} {name} {model} {year} costs {amount} {currency} \n");

    return jsonObject.Count;
}

We first convert the SingleJsonObject string to a JObject. Then, we use the Value<T>() method to get values from the JObject and assign them to local variables. In cases where we have nested JSON, we extract the Jobject first and chain the call for the specific type.

Compared to the first approach, using the Value<T>() method is less tedious when working with a nested JSON object because we can chain our calls. However, to get the correct value, we have to pass the right key.

Using the SelectToken() Method

To continue, let’s add a new method to the JObjectManipulation class:

public int GetValuesUsingSelectToken()
{
    var jsonObject = JObject.Parse(SingleJsonObject);

    var name = (string)jsonObject.SelectToken("name");
    var make = (string)jsonObject.SelectToken("make");
    var model = (string)jsonObject.SelectToken("model");
    var year = (int)jsonObject.SelectToken("year");
    var amount = (int)jsonObject.SelectToken("price.amount");
    var currency = (string)jsonObject.SelectToken("price.currency");

    Console.WriteLine($"A {make} {name} {model} {year} costs {amount} {currency} \n");

    return jsonObject.Count;
}

The first step is creating a JObject from the JSON string. After that, we call the SelectToken method passing the keys as parameters. Then, we cast the values to appropriate data types. 

When working with more complex JSON data, the SelectToken() method would be the best choice of the three. Beyond basic usage, it offers some advanced capabilities like:

  • Querying JSON arrays using indexes
  • Support for JSONPath queries
  • Support for LINQ queries

When we call each of these methods discussed, we get this output in the console:

A Dodge Charger RT 2019 costs 36100 USD

In each of the approaches we have covered so far, we will get an exception or a default value for the converted type whenever the JSON key is missing. Let’s look at an alternative approach.

Using the JObject.TryGetValue() Method

The TryGetValue takes both the key and output variable as parameters. Then, it tries to get the JSON token that matches the specified key. If the token is found, this method returns true otherwise, it returns false

Let’s demonstrate this: 

public int GetValuesUsingTryGetValue()
{
    JObject jsonObject = JObject.Parse(SingleJsonObject);

    if (jsonObject.TryGetValue("name", out JToken nameToken))
    {
        string name = (string)nameToken;
        Console.WriteLine($"Name: {name}");
    }

    if (jsonObject.TryGetValue("make", out JToken makeToken))
    {
        string make = (string)makeToken;
        Console.WriteLine($"Make: {make}");
    }

    if (jsonObject.TryGetValue("price", out JToken priceToken) && priceToken is JObject priceObject)
    {
        if (priceObject.TryGetValue("amount", out JToken amountToken))
        {
            int amount = (int)amountToken;
            Console.WriteLine($"Price amount: {amount}");
        }

        if (priceObject.TryGetValue("currency", out JToken currencyToken))
        {
            string currency = (string)currencyToken;
            Console.WriteLine($"Price currency: {currency}");
        }
    }

    return jsonObject.Count;
}

We are passing the keys for which we want to get values together with JToken objects. If the method returns true, we cast the JToken objects into specified types. 

Similarly, we have a nested JSON price object. In this case, we first call the TryGetValue method passing the price key. If this returns true, we use the is operator to check if priceToken is a JObject. If this check returns true as well, we proceed to access the values of the price nested JSON object.

Calling this method, we get:

Name: Charger
Make: Dodge
Price amount: 36100
Price currency: USD

Using TryGetValue method, if any of the keys we are trying to access is missing, the method returns false. This way, we are not trying to access the values of a non-existent key.

The appropriate use case for this method is when working with JSON data from an API where the data does not have a fixed structure. In this case, if a key is missing, our application won’t break.

Conclusion

In this article, we have learned how to get value by key from JObject in C# to process JSON data. We hope this guide will be of assistance when developing future applications. 

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!