Written byCode-Labyrinth|Updated date January 30, 2023|0
In this article, we will learn about different waysGet value by key from JObject in C#.
To download the source code for this article you can visit ourGitHub-Repository.
Let us begin.
What is JObject?
JObject is a class type in theJson.NETLibrary representing a JSON object. The class provides methods that allow us to manipulate JSON data, such as:
- Creating JSON objects
- Parse JSON and read data
- Adding data to JSON objects
We won't go into each of these use cases. Instead, we only look at parsing JSON and reading data. We also covered how to do ititerate over a JSON arrayand howDeserialize JSON into a dynamic objectwith Json.Net.
data preparation
Our main focus in this article is learning how to read data from a JSON object using JObject. So let's create a simple console application and install itJson.NET
library with the command:
NuGet\Install-Package Newtonsoft.Json
After that we add a new oneTest dates
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 look at different ways to get the 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 gives us flexibility in reading values from a JSON object. We'll look at four ways to do this:
- Passing the key as an index
- Use of
JObject.Value<T>()
Method - Use of
JObject.SelectToken()
Method - Use of
JObject.TryGetValue()
Method
First we add a new oneJObjectManipulation
Class we will use to illustrate these four approaches:
public class JObjectManipulation{ public string SingleJsonObject { get; Sentence; } public JObjectManipulation() { InitializeData(); } public void InitializeData() { var testData = new TestData(); SingleJsonObject = testData.GenerateSingleJsonObject(); }}
In this class we initialize theSingleJsonObject
class property in theInitializeData()
method, which we then call in the constructor.
Passing the key as an index
ImJObjectManipulation
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($"One {make} {name} {model} {year} costs {amount} {currency} \n"); return jsonObject.Count ;}
We first convert theSingleJsonObject
string to aJObject
useJObject.Parse
. To retrieve values from the JSON object,We pass the keys to the JObject as indexes, where the notation in square brackets is used. After getting the values, we cast them to the desired type.
ThePreis
key has JSON nested withCrowd
AndCurrency
key-value pairs. To get these values, we follow the same steps, first converting the value ofPreis
to a JObject with a cast:
Would you like to join the Code Maze team, help us produce more great .NET/C# content andget paid?>> JOIN US! <<
var Price = (JObject)jsonObject["Price"]
Then we access the values ofCrowd
AndCurrency
using the index of the resultJObject
:
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 deep value can be very tedious. There is theValue<T>()
method comes into play.
Let's tackle it next.
Using the Value<T>() method
With this methodWe pass the key directly to the method as a parameter. In addition, we also pass the appropriate type as a type argument to theValue<T>
Method. The method then returns the already cast value.
Let's create a new oneGetValuesUsingValueMethod
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 Betrag = jsonObject.Value<int>("Preis.Betrag"); var currency = jsonObject.Value<string>("price.currency"); Console.WriteLine($"Ein {Marke} {Name} {Modell} {Jahr} kostet {Betrag} {Währung} \n"); gib jsonObject.Count zurück;}
We first convert theSingleJsonObject
string to aJObject
. Then we use thoseValue<T>()
method to get values from the JObject and assign them to local variables.In cases where we have nested JSON, we pass the keys separated by.
Operator.
Compared to the first approach, with whichValue<T>()
method is less tedious when working with a nested JSON object. However, to get the right value, we need to pass the right key.
Would you like to join the Code Maze team, help us produce more great .NET/C# content andget paid?>> JOIN US! <<
Using the SelectToken() method
To continue, let's add a new method to thisJObjectManipulation
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 Betrag = (int)jsonObject.SelectToken("Preis.Betrag"); var currency = (string)jsonObject.SelectToken("price.currency"); Console.WriteLine($"Ein {Marke} {Name} {Modell} {Jahr} kostet {Betrag} {Währung} \n"); gib jsonObject.Count zurück;}
The first step is to create oneJObject
from the JSON string. After that we callselect tokens
Method that passes the keys as parameters. Then we convert the values into appropriate data types.
When working with more complex JSON data, theSelectToken()
method would be the best choice of the three. Beyond the basic usage, it offers some advanced features like:
- Querying JSON arrays using indexes
- Support for JSONPath queries
- Support for LINQ queries
When we call each of these discussed methods, we get this output in the console:
A Dodge Charger RT 2019 costs 36100 USD
In each of the approaches we've covered so far,We get an exception when the JSON key is missing. Let's look at an alternative approach.
Using the JObject.TryGetValue() method
TheTryGetValue
takes both the key and the output variable as parameters. It then attempts to get the JSON token that matches the given key. If the token is found, this method returnsTRUE
otherwise it returnsINCORRECT
.
Let's demonstrate this:
Would you like to join the Code Maze team, help us produce more great .NET/C# content andget paid?>> JOIN US! <<
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($"Preisbetrag: {Betrag}"); } if (priceObject.TryGetValue("currency", out JToken currencyToken)) { string currency = (string)currencyToken; Console.WriteLine($"Währung des Preises: {Währung}"); } } return jsonObject.Count;}
We pass the keys for which we want to get values along withJToken
objects. If the method returns true, we cast theJToken
objects into specific types.
Likewise, we have a nested JSONPreis
Object. In this case, we call the firstTryGetValue
Method that passes thePreis
Button. If this returns true, we use theIs
operator to check whetherPriceToken
is aJObject
. If this check also returns true, we proceed to access the values ofPreis
nested JSON object.
When we call this method, we get:
Name: ChargerBrand: DodgePrice Amount: 36100Price Currency: USD
UseTryGetValue
method, if any of the keys we want to access are missing, the method will return false. This way we don't try to access the values of a key that doesn't exist.
The appropriate use case for this method is whenWorking with JSON data from an API where the data has no fixed structure. In this case, if a key is missing, our application will not break.
Diploma
In this article, we learned how to get values by key from JObject in C# to process JSON data. We hope this guide will be useful in developing future applications.