Уровень пользовательского интерфейса вызывает API с помощью общего репозитория API, созданного с помощью HttpClient.
Структура моего проекта примерно следующая:
Код: Выделить всё
Core
└─ DataAccess
└─ Repository
└─ ApiRepositoryBase.cs
Kutuphane.API
└─ Controllers
└─ DilController.cs
Kutuphane.Model
└─ Entity
└─ Dil.cs
Kutuphane.UI
└─ Services
API возвращает следующий JSON:
Код: Выделить всё
{
"data": [
{
"dilId": 1,
"dilAdi": "Türkçe",
"dilKodu": "tr",
"aktifMi": true
},
{
"dilId": 2,
"dilAdi": "İngilizce",
"dilKodu": "en",
"aktifMi": true
}
],
"message": null,
"isSuccess": true
}
Код: Выделить всё
public class Dil : IEntity
{
public short DilId { get; set; }
public string DilAdi { get; set; }
public string DilKodu { get; set; }
public bool AktifMi { get; set; } = true;
}
Код: Выделить всё
public async Task GetListAsync(string endpoint, Expression? filter = null)
{
try
{
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(_baseUrl.Trim());
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _token);
var response = await httpClient.GetAsync($"api/{endpoint}");
if (!response.IsSuccessStatusCode)
return new ErrorDataResult(response.ReasonPhrase ?? "Api error");
var data = await response.Content.ReadFromJsonAsync();
if (data == null)
return new ErrorDataResult("Deserialization failed");
if (filter != null)
{
var compiledFilter = filter.Compile();
data = data.Where(compiledFilter).ToList();
}
return new SuccessDataResult(data);
}
catch (Exception ex)
{
return new ErrorDataResult(ex.Message);
}
}
Код: Выделить всё
System.Text.Json.JsonException:
The JSON value could not be converted to
System.Collections.Generic.List.
Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Код: Выделить всё
var data = await response.Content.ReadFromJsonAsync();
Поскольку ответ API содержит список внутри свойства data, а не корневой массив JSON, каков правильный способ десериализации этого ответа в сценарии общего репозитория?
Подробнее здесь: https://stackoverflow.com/questions/799 ... se-contain
Мобильная версия