I am developing a layered .NET project with API, BLL, DAL, and UI layers.
The UI layer calls the API using a generic API repository built with HttpClient.
My project structure is roughly:
Core
└─ DataAccess
└─ Repository
└─ ApiRepositoryBase.cs
Kutuphane.API
└─ Controllers
└─ DilController.cs
Kutuphane.Model
└─ Entity
└─ Dil.cs
Kutuphane.UI
└─ Services
API Response
The API returns the following JSON:
{
"data": [
{
"dilId": 1,
"dilAdi": "Türkçe",
"dilKodu": "tr",
"aktifMi": true
},
{
"dilId": 2,
"dilAdi": "İngilizce",
"dilKodu": "en",
"aktifMi": true
}
],
"message": null,
"isSuccess": true
}
Entity
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;
}
Generic API Repository Method
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);
}
}
Exception
System.Text.Json.JsonException:
The JSON value could not be converted to
System.Collections.Generic.List.
Path: $ | LineNumber: 0 | BytePositionInLine: 1.
The exception occurs on this line:
var data = await response.Content.ReadFromJsonAsync>();
Question
Since the API response contains the list inside a data property rather than being a root JSON array, what is the correct way to deserialize this response in a generic repository scenario?