I can't figure out why System.Text.Json won't deserialize this simple JSON string to my specified .NET type. I'm getting the Each parameter in the deserialization constructor on type 'MenuItem' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive
error message, even though I have mapped every property — name
, url
, and permissions
— in my MenuItem
constructor.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
public static void Main()
{
try
{
var json = @"
[
{
""name"": ""General Info"",
""url"": ""/Info"",
""permissions"": []
},
{
""name"": ""Settings"",
""url"": ""/Settings"",
""permissions"": [
""Admin""
]
}
]";
Console.WriteLine(json);
var menu = new Menu(json);
Console.WriteLine("Deserialization success");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
public class Menu
{
public Menu(string json)
{
var items = JsonSerializer.Deserialize<List<MenuItem>>(json);
MenuItems = items.AsReadOnly();
}
public IReadOnlyList<MenuItem> MenuItems { get; }
}
public class MenuItem
{
[JsonConstructor]
public MenuItem
(
string name,
string url,
List<Permission> permissions
)
{
this.Name = name;
this.Url = url;
this.Permissions = (permissions ?? new List<Permission>()).AsReadOnly();
}
public string Name { get; }
public string Url { get; }
public IReadOnlyList<Permission> Permissions { get; }
}
public enum Permission
{
Admin,
FinancialReporting
}
Can anyone tell me what I'm doing wrong?
JsonSerializerOptions.PropertyNameCaseInsensitive = true
as shown in JsonSerializer.Deserialize fails. – Inga