System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[Update]
Я пишу бота для телеграмма на C#-е
Я хочу чтобы при запуске кода, он писал мне Id и Username бота
Но при запуске пишет:
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[Update]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Всё что я находил на сайтах было решением не моей проблемы, которое нельзя применить к моему коду
код:
using System.Text.Json.Serialization;
using System.Net.Http.Headers;
using System.Text.Json;
using HttpClient client = new();
var updates = await ProcessAsync(client);
foreach (var upd in updates)
{
Console.WriteLine($"Id: {upd.Id}");
Console.WriteLine($"Username: {upd.Username}");
Console.WriteLine();
}
static async Task<List<Update>> ProcessAsync(HttpClient client)
{
await using Stream stream = await client.GetStreamAsync("https://api.telegram.org/bot(CENSORED)/getMe");
var updates = await JsonSerializer.DeserializeAsync<List<Update>>(stream);
return updates ?? new();
}
using System;
using System.Text.Json.Serialization;
public sealed record class Update(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("username")] string Username){}
json:
{
"ok": true,
"result": {
"id": 6631136786,
"is_bot": true,
"first_name": "MoneySys",
"username": "MoneySysBot",
"can_join_groups": true,
"can_read_all_group_messages": false,
"supports_inline_queries": false
}
}
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
В JSON
[]- массив, коллекция{}- объект, запись
Вы пытаетесь объект распарсить как массив, отсюда и ошибка.
Как-то так получится:
public sealed record Response<T>(
[property: JsonPropertyName("ok")] bool Ok,
[property: JsonPropertyName("result")] T Result,
[property: JsonPropertyName("description")] string Description
);
static Task<Response<T>> ProcessAsync<T>(HttpClient client)
{
return client.GetFromJsonAsync<Response<T>>("https://api.telegram.org/bot(CENSORED)/getMe");
}
var response = await ProcessAsync<Update>(client);
if (response.Ok)
{
var update = response.Result;
Console.WriteLine($"Id: {update.Id}");
Console.WriteLine($"Username: {update.Username}");
}
else
{
Console.WriteLine(response.Description);
}