Resolução:
Carro.cs
using System.Text.Json.Serialization;
namespace DesafiosCSharp03._02Desafio.Modelos
{
internal class Carro
{
[JsonPropertyName("marca")]
public string? Marca { get; set; }
[JsonPropertyName("modelo")]
public string? Modelo { get; set; }
[JsonPropertyName("ano")]
public int? Ano { get; set; }
[JsonPropertyName("tipo")]
public string? Tipo { get; set; }
[JsonPropertyName("motor")]
public string? Motor { get; set; }
[JsonPropertyName("transmissor")]
public string? Transmissor { get; set; }
public void ExibirInformacoes()
{
Console.WriteLine($"Marca: {Marca}");
Console.WriteLine($"Modelo: {Modelo}");
Console.WriteLine($"Ano: {Ano}");
Console.WriteLine($"Tipo: {Tipo}");
Console.WriteLine(new string('-', 30));
}
}
}
Program.cs
Console.Clear();
using (HttpClient client = new HttpClient())
{
string resposta = await client.GetStringAsync("https://raw.githubusercontent.com/ArthurOcFernandes/Exerc-cios-C-/curso-4-aula-2/Jsons/Carros.json");
try
{
var carros = JsonSerializer.Deserialize<List<Carro>>(resposta)!;
foreach (var carro in carros)
{
carro.ExibirInformacoes();
}
}
catch (Exception ex)
{
Console.WriteLine($"Ocorreu um erro ao obter os dados: {ex.Message}");
}
}