Home
Tags: C# | HttpClient | JSON Deserialization | Networking | HTTP | HTTP Response | HTTP POST Response

Responses. JSON Deserialization

Option 1

public async Task<Product> GetProductAsync(int id)
{
    var response = await HttpClientSingleton.Instance.GetAsync($"products/{id}");
    
    response.EnsureSuccessStatusCode();
    var product = await response.Content.ReadFromJsonAsync<Product>();
    
    return product ?? throw new Exception("Product not found");
}

Option 1

private async Task<List<Fruit>> GetFruits()
{
    var response = await HttpClientSingleton.Instance.GetAsync($"http://localhost:5147/fruits");

    response.EnsureSuccessStatusCode();
    
    var content = await response.Content.ReadAsStringAsync();
    var fruits = JsonSerializer.Deserialize<List<Fruit>>(content);
    return fruits;
}