System.InvalidOperationException Json

using System.Text.Json;
using (FileStream fs = new FileStream("country.json", FileMode.OpenOrCreate))
{
    country country1 = new country("Russia", 144000000, 17100000);
    await JsonSerializer.SerializeAsync<country>(fs, country1);
    Console.WriteLine("Data has been saved to file");
}

using (FileStream fs = new FileStream("country.json", FileMode.OpenOrCreate))
{
    country? country1 = await JsonSerializer.DeserializeAsync<country>(fs);
    Console.WriteLine($"Country: {country1?.Name}  residents: {country1?.residents} territory: {country1?.territory}");
}

class country
{
    public string Name { get; }
    public int residents { get; set; }
    public int territory { get; set; }
    public country(string name, int res, int terr)
    {
        Name = name;
        residents = res;
        territory = terr;
    }
}

Ошибка:

"Each parameter in the deserialization constructor on type 'country' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'JsonSerializerOptions.IncludeFields' is enabled. The match can be case-insensitive."

System.InvalidOperationException: "Each parameter in the deserialization constructor on type 'country' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'JsonSerializerOptions.IncludeFields' is enabled. The match can be case-insensitive."
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ContinueDeserialize[TValue](ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.<ReadFromStreamAsync>d__76`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Program.<<Main>$>d__0.MoveNext() in /Users/lemintare/Projects/LR7_json/LR7_json/Program.cs:11

Изначально я скопировал код такой:

using System.Text.Json;
 
// сохранение данных
using (FileStream fs = new FileStream("user.json", FileMode.OpenOrCreate))
{
    Person tom = new Person("Tom", 37);
    await JsonSerializer.SerializeAsync<Person>(fs, tom);
    Console.WriteLine("Data has been saved to file");
}
 
// чтение данных
using (FileStream fs = new FileStream("user.json", FileMode.OpenOrCreate))
{
    Person? person = await JsonSerializer.DeserializeAsync<Person>(fs);
    Console.WriteLine($"Name: {person?.Name}  Age: {person?.Age}");
}
 
class Person
{
    public string Name { get;}
    public int Age { get; set; }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

И начал заменять значения просто под свою задачу (надо было сериализовать структуру страны). Код до изменений работает.


Ответы (1 шт):

Автор решения: gil9red

У вас названия полей и аргументов в конструкторе не совпадают

Накидал пример:

using System;
using System.Text.Json;

class Country
{
    public string Name { get; }
    public int Residents { get; set; }
    public int Territory { get; set; }
    
    public Country(string name, int residents, int territory)
    {
        Name = name;
        Residents = residents;
        Territory = territory;
    }
}

public class HelloWorld
{
    public static void Main(string[] args)
    {
        Country country1 = new Country("Russia", 144000000, 17100000);
        string json2 = JsonSerializer.Serialize(country1);
        Console.WriteLine("Data has been saved to: " + json2);
        // Data has been saved to: {"Name":"Russia","Residents":144000000,"Territory":17100000}
        
        Country? country2 = JsonSerializer.Deserialize<Country>(json2);
        Console.WriteLine($"Country: {country2?.Name}  residents: {country2?.Residents} territory: {country2?.Territory}");
        // Country: Russia  residents: 144000000 territory: 17100000
    }
}
→ Ссылка