using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
public int Id { get; set; }
public string Name { get; set; }
public string ISO2 { get; set; }
public string ISO3 { get; set; }
public ICollection<City> Cities { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
public static async Task Test()
var fileName = "Question75159862.json";
await File.WriteAllTextAsync(fileName, GetJson());
var countries = new List<Country>();
await using var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true);
var options = new JsonSerializerOptions
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
await foreach (var country in JsonSerializer.DeserializeAsyncEnumerable<Country>(stream, options))
if (country.Cities != null)
foreach (var city in country.Cities)
var clone = JsonSerializer.Deserialize<City>(JsonSerializer.SerializeToUtf8Bytes(city));
city.CountryId = country.Id;
Console.WriteLine("Deserialized and re-serialized {0}:", countries);
var writeOptions = new JsonSerializerOptions
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
Console.WriteLine(JsonSerializer.Serialize(countries, writeOptions));
static string GetJson() =>
"name":"‘Alāqahdārī Dīshū"
public static async Task Main(string[] args)
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");