Microsoft has introduced LINQ to JSON, a highly anticipated feature in C#. This article explores how to retrieve JSON data from an API and parse it using LINQ. We will leverage the JsonDocument class and provide additional code examples and details to demonstrate the process.
To begin, let’s write a simple program that retrieves JSON data from the popular FAKE API server, jsonplaceholder. Using HttpClient
, we send a request to the API endpoint and obtain the JSON response.
async Task Main()
{
using var client = new HttpClient();
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
var json = await client.GetStringAsync("todos");
ParseJSON(json);
}
If we hit the API endpoint https://jsonplaceholder.typicode.com/todos
from the browser, we get a response like the following JSON data:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
.....
Once the JSON data is downloaded, we can load the JSON string into the ParseJSON
method and apply LINQ
expressions on the root elements. In this case, the response is an array of todo items, so we’ll use EnumerateArray
to iterate over them.
private void ParseJSON(string jsonData)
{
using var document = JsonDocument.Parse(jsonData);
var query =
from todo in document.RootElement.EnumerateArray()
select new
{
userId = todo.GetProperty("userId").GetInt32(),
title = todo.GetProperty("title").GetString(),
completed = todo.GetProperty("completed").GetBoolean()
};
Console.WriteLine(query);
}
In the ParseJSON method, we use the JsonDocument class to parse the JSON data. We define a LINQ query that selects specific properties from each todo item, such as userId, title, and completed. We then iterate over the query results and print the details to the console.
It’s worth noting that the JsonDocument
class optimizes memory usage by utilizing pooled memory resources. This minimizes the impact on the garbage collector (GC) in high-usage scenarios. It’s important to properly dispose of the JsonDocument
object to ensure efficient memory management.
By leveraging LINQ to JSON, you can effectively parse and extract relevant data from JSON responses in C#. This feature simplifies working with JSON data and enhances the capabilities of your applications.