I’ve got a frontend application which is producing a JSON object (lets call it a RuleGroup). Each RuleGroup contains a list of either subgroups or nodes. Below is a rough example of what this may look like
{
"combinator": "OR", <---RuleGroup
"not": true,
"criteria": [
{
"field": "path", <---RuleCriteria
"key": "",
"value": "",
"operator": "="
},
{
"combinator": "AND", <---RuleGroup
"not": false,
"criteria": [
{
"field": "header", <---Node
"key": "",
"value": "",
"operator": "="
},
]
}
]
}
How can I deserialise an object like this on my API controller?
I’ve tried setting up some types like this however my Criteria list ends up full of BaseRule objects that cannot be cast to the other two types.
public class RuleGroup : BaseRule
{
public string Combinator { get; set; }
public bool Not { get; set; }
public List<BaseRule> Criteria { get; set; }
}
public class RuleCriteria : BaseRule
{
public string Field { get; set; }
public string Operator { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
public class BaseRule
{
}
I suspect what I need is something like https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism?pivots=dotnet-8-0#polymorphic-type-discriminators however I dont really want to add a dedicated type field to my data.
My last option is to manually deserialise the data back into the appropriate objects.
If theres a way to do this without me rolling my own deserialiser, please let me know
Thanks