Manipulating JSON objects is a common operation in applications. In this article, we will look at different ways of iterating over JSON objects in C#.
Let’s start.
Data Preparation
Before we begin, let’s first set up a new console application.
We also need a set of JSON data to work with, so let’s add a new class called TestData
. Inside the class, let’s also add a new GenerateJsonData()
method that returns a JSON string:
public class TestData { public string GenerateJsonData() { const string jsonData = $$""" [ { "name":"John Doe", "age": 30, "department":"IT" }, { "name":"Antonio Weber", "age": 20, "department":"Finance" }, { "name":"Jane Doe", "age": 25, "department":"Legal" }, { "name":"Ramiro Buck", "age": 28, "department":"IT" }, { "name":"Shirley Pearson", "age": 30, "department":"Human Resource" } ] """ ; return jsonData; } }
Now that we have all the data we need, let’s look at the different ways we can iterate over a JSON object in C#.
Iterating Over Json Objects Using Json.NET
Json.NET is a third-party library that provides a convenient way of working with JSON. It is available as a NuGet Package, and we install it using the package manager console by running the command:
NuGet\Install-Package Newtonsoft.Json
Using Json.NET
, we can iterate over a JSON object using one of the three ways:
- Using a dynamic object
- Using the JArray object
- Using statically typed object
To illustrate these different approaches, let’s create a new JsonIteration
class:
public class JsonIteration { public string Json { get; set; } public JsonIteration() { Json = new TestData().GenerateJsonData(); } }
In the constructor, we assign the Json
property to the JSON string we generate in the TestData
class.
In this class, we will be adding new methods to show how we can iterate over JSON objects in C#.
Iterating Using a Dynamic Object
Let’s add a new IterateOverJsonDynamically()
method to the class:
public int IterateOverJsonDynamically() { var jsonData = JsonConvert.DeserializeObject<dynamic>(Json); foreach (var data in jsonData) { var name = data.name; var age = data.age; var department = data.department; Console.WriteLine($"Name: {name}, Age: {age}, Department: {department}"); } var count = jsonData.Count; return count; }
In this method, we first deserialize Json
into a dynamic object. Here, we are passing dynamic
as a type argument to the generic DeserializeObject<>
method call. This way, we get a dynamic object as a result of deserialization.
This is just but one way to iterate over a JSON object. However, the Json.NET
library also provides us with another method, JArray.Parse
to help us iterate over a JSON object.
Iterating Using the JArray Object
JArray.Parse
method takes a JSON string as a parameter. After that, it reads the JSON string and loads it into a JArray object. To read the values of the object, we pass the keys using square bracket notation. In this case, the keys are indexes for which values we’d like to get.
To demonstrate this, let’s create a new method in the JsonIteration
class:
public int IterateUsingJArray() { var jsonArray = JArray.Parse(Json); foreach (var data in jsonArray) { var name = (string)data["name"]; var age = (int)data["age"]; var department = (string)data["department"]; Console.WriteLine($"Name: {name}, Age: {age}, Department: {department}"); } var count = jsonArray.Count; return count; }
In this method, we first convert the JSON string into a JArray object. After that, we loop over the JArray object, assigning values to the different variables. Take note of how we pass the JSON keys to get their values. Outside the loop, we get the count and return it.
Iterating Over JSON Objects Using a Statically Typed Object
Using Json.NET, we can also explicitly specify the type of our data.
For this, let’s create a new Employee
class:
public class Employee { public string Name { get; set; } public int Age { get; set; } public string Department { get; set; } }
In our JsonIteration
class, let’s add a new method:
public List<Employee> IterateUsingStaticallyTypedObject() { var employees = JsonConvert.DeserializeObject<List<Employee>>(Json); foreach (var employee in employees) { var name = employee.Name; var age = employee.Age; var department = employee.Department; Console.WriteLine($"Name: {name}, Age: {age}, Department: {department}"); } return employees; }
In this method, we first deserialize the JSON string into a list of employees. This way, we get a typed list of employees. Then, we loop over the list assigning values to the properties of the JsonIteration
class.
Iterating Over Json Objects Using System.Text.Json
System.Text.Json
also enables us to deserialize and iterate over JSON objects. We have extensively covered it here. If you feel the need to brush up before we proceed, please check out the article.
Now, let’s add a new IterateUsingSystemJson()
method to our class:
public List<Employee> IterateUsingSystemJson() { var employees = JsonSerializer.Deserialize<List<Employee>>(Json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); foreach (var employee in employees) { var name = employee.Name; var age = employee.Age; var department = employee.Department; Console.WriteLine($"Name: {name}, Age: {age}, Department: {department}"); } return employees; }
In this method, we first deserialize the JSON string into a list of statically typed employees. We pass an additional argument of type JsonSerializerOptions
to the Deserialize<>()
method call in order to configure the deserialization to ignore case sensitivity (a step we didn’t need with Json.Net).
For each of the examples we have covered, the output to the console is:
Name: John Doe, Age: 30, Department: IT Name: Antonio Weber, Age: 20, Department: Finance Name: Jane Doe, Age: 25, Department: Legal Name: Ramiro Buck, Age: 28, Department: IT Name: Shirley Pearson, Age: 30, Department: Human Resource
A Few Notes About Json.NET and System.Text.Json
Having come this far, let’s finish with a summary on Json.NET
and System.Text.Json
.
Json.NET
comes with a lot of options by default:
- Case-insensitivity
- No depth limit
- Allowing comments and trailing commas
- Support for strings with single as well as double quotes
- Support for non-string values
System.Text.Json
on the other hand, requires us to configure it so we can get desired results. An example of configuration is removing case sensitivity by adding the options parameters like we needed to do in our example code.
Conclusion
When working with APIs, processing JSON data is a vital part of development. In this article, we have covered a number of ways of iterating over JSON objects in C# and extracting data for further use. We hope this information sets you up in the right direction.
Well done. Awesome article
Thank you Sue.