I recommend you to read your json data async because this method have overload that takes stream as an input, so you can read data in two strings of code like this:
ProjFolder\Program.cs
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using StackOverflow.Models;
namespace StackOverflow
{
class Program
{
static async Task Main(string[] args)
{
using var openStream = File.OpenRead(@"D:\Code\test.json");
var result = await JsonSerializer.DeserializeAsync<Root>(openStream);
// You need to get car2 Costo
var costo = result.Car2.Costo;
}
}
}
ProjFolder\Models\Root.cs
using System.Text.Json.Serialization;
namespace StackOverflow.Models
{
public class Root
{
[JsonPropertyName("car1")]
public Car Car1 { get; set; }
[JsonPropertyName("car2")]
public Car Car2 { get; set; }
}
}
ProjFolder\Models\Car.cs
namespace StackOverflow.Models
{
public class Car
{
public string CasaAutomobilistica { get; set; }
public string Modello { get; set; }
public string AnnoImmatricolazione { get; set; }
public string Targa { get; set; }
public int KM { get; set; }
public bool Finanziamento { get; set; }
public int Porte { get; set; }
public int Costo { get; set; }
}
}
{
"car1":
{
"CasaAutomobilistica": "Fiat",
"Modello": "500",
"AnnoImmatricolazione": "2017",
"Targa": "AZ978AG",
"KM": 120000,
"Finanziamento" : true,
"Porte" : 5,
"Costo" : 6000
},
"car2":
{
"CasaAutomobilistica": "BMW",
"Modello": "Serie 1",
"AnnoImmatricolazione": "2019",
"Targa": "BC978AG",
"KM": 150000,
"Finanziamento" : false,
"Porte" : 3,
"Costo" : 12000
}
}