JsonSerialization Help
I have this class in C# (functionallity removed)
A record that allows parsing of multiple commands:
and this is the json file:
I get this error:
Serialization has the
public class Command
{
[JsonIgnore]
public IEnumerable<Flag> Flags => _flags;
[JsonIgnore]
public IEnumerable<string> AllowedFlags => _allowedFlags;
[JsonPropertyName("command")]
public string Name { get; }
[JsonPropertyName("allowedFlags")]
private readonly HashSet<string> _allowedFlags;
[JsonPropertyName("flags")]
private readonly List<Flag> _flags = [];
[JsonPropertyName("arguments")]
private readonly List<string> _arguments;public class Command
{
[JsonIgnore]
public IEnumerable<Flag> Flags => _flags;
[JsonIgnore]
public IEnumerable<string> AllowedFlags => _allowedFlags;
[JsonPropertyName("command")]
public string Name { get; }
[JsonPropertyName("allowedFlags")]
private readonly HashSet<string> _allowedFlags;
[JsonPropertyName("flags")]
private readonly List<Flag> _flags = [];
[JsonPropertyName("arguments")]
private readonly List<string> _arguments;A record that allows parsing of multiple commands:
[JsonSerializable(typeof(CommandConfig))]
public record CommandConfig
{
[JsonPropertyName("commands")]
public IList<Command> Commands { get; init; }
}[JsonSerializable(typeof(CommandConfig))]
public record CommandConfig
{
[JsonPropertyName("commands")]
public IList<Command> Commands { get; init; }
}and this is the json file:
{
"commands": [
{
"command": "log",
"allowedFlags": ["pretty"],
"arguments": [],
"flags": {
"Name": "pretty",
"Value": "%h~%cn~%ch~%cI~%s"
}
}
]
}{
"commands": [
{
"command": "log",
"allowedFlags": ["pretty"],
"arguments": [],
"flags": {
"Name": "pretty",
"Value": "%h~%cn~%ch~%cI~%s"
}
}
]
}I get this error:
Unhandled exception. System.InvalidOperationException: Each parameter in the deserialization constructor on type 'BL.Core.Command' 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. Unhandled exception. System.InvalidOperationException: Each parameter in the deserialization constructor on type 'BL.Core.Command' 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. Serialization has the
IncludeFieldsIncludeFields option set to true and all properties has JsonIgnoreJsonIgnore on them. Can someone please help?