Recent C# version Microsoft Added the much-awaited feature LINQ to JSON. Yes, You are. Right now, you can parse JSON data using LINQ.
This article will show you how to get JSON from the API and parse using LINQ.
JsonDocument Class
Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values.
In this Demo, I am using a popular FAKE API server. jsonplaceholder
If you hit the above API from the browser, you get a response something like below.
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
.....
Let’s write a simple program to get the JSON data from the server.
async Task Main()
{
using var client = new HttpClient();
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
var json = await client.GetStringAsync("todos");
ParseJSON(json);
}
Once JSON data is download, you can load the JSON string data in the method, and then you can apply the LINQ expression on the root elements. In our case, the response is an array of todos item so that EnumerateArray
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);
}
Regarding the performance as per the Microsoft
JsonDocument class utilizes resources from pooled memory to minimize the impact of the garbage collector (GC) in high-usage scenarios. Failure to properly dispose this object will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework.