Search code examples
c#.netjson.netjson-deserialization

Deserialize JSON with dynamic key-value pair to class


I have the following JSON:

{
    "ruleName": "PhoneNumber",
    "ruleSetInput": [
        {
            "PersonCode": "85782",
            "PhoneTypeId": "1",
            "PhoneClassId": "0",
            "DiallingCode": "021",
            "PhoneNumber": "9321662",
            "Extension": "",
            "Status": "",
            "User": "2",
            "DateCapturd": ""
        }
    ]
}

The JSON won't always have the same fields in the ruleSetInput node. I need to map each value under ruleSetInput to a class with the following class:

public class Parameter
{
    public string Name { get; set; }
    public string Value { get; set; }

    [JsonIgnore]
    public int Type { get; set; }

}

As an example Parameter would be a list and contain a value of:

Name: "PersonCode", Value: "85782"

How can I dynamically create this mapping? I have tried Newtonsoft.Json but the mapping will only work if the object that I am deserializing has this exact structure.


Solution

  • You could make ruleSetInput a Dictionary<string, string> and then construct your Parameter instances from the key-value pairs using ruleSetInput.Select(kv => new Parameter { Name = kv.Key, value = kv.Value }