I need to have the System.Text.Json.JsonSerializer
be able to deserialize this nested Dictionary type structure, but I'm getting the following error:
Unable to cast object of type 'System.Text.Json.JsonElement' to type 'System.String'.
I have the following JSON
{
"ACL": {
"granted": {
"Business": {
"Delete": [
"Customer1",
"Customer2"
]
},
"Account": {
"Create": [
"Customer1",
"Customer3"
]
}
}
}
}
Going into the following model
using System.Collections.Specialized;
public record AclRecord
{
public Dictionary<string, Dictionary<string, Dictionary<string, StringCollection>>> ACL { get; set; }
}
What would a JsonConverter to deserialize this type of triple nested Dictionary type structure look like?
CodePudding user response:
If you're willing to use List<string>
instead of StringCollection
for your deserialization target, this will work out of the box:
public record AclRecord
{
public Dictionary<string, Dictionary<string, Dictionary<string, List<string>>>> ACL { get; set; }
}
var obj = JsonSerializer.Deserialize<AclRecord>(json);
If you MUST use StringCollection
, you will need to write a custom converter.