Query-параметры API в C#
После знака "?" в URI идут пары
"имя=значение", разделённые "&".
Сервер фильтрует коллекцию до ответа - клиент
получает уже урезанный JSON-массив.
Запрос комментариев с "postId=1" на
typicode возвращает только записи с этим
полем. После разбора проверим, что у первого
элемента postId равен 1:
using System.Net.Http;
using System.Text.Json;
using HttpClient client = new();
string json = await client.GetStringAsync("https://jsonplaceholder.typicode.com/comments?postId=1");
using JsonDocument doc = JsonDocument.Parse(json);
Console.WriteLine(doc.RootElement[0].GetProperty("postId").GetInt32());
Если фильтр ничего не нашёл, ответ может быть
успешным, а массив - пустым. Для
postId 99999 длина массива равна нулю:
using System.Net.Http;
using System.Text.Json;
using HttpClient client = new();
string json = await client.GetStringAsync("https://jsonplaceholder.typicode.com/comments?postId=99999");
using JsonDocument doc = JsonDocument.Parse(json);
Console.WriteLine(doc.RootElement.GetArrayLength());
Запросите "albums?userId=3" на typicode
и выведите в консоль длину массива и
title первого альбома.