Search code examples
c#json.netserialization

Serialize Json object with properties dynamically with dictionary


I need to serialize a response of an object with a dictionary dynamically. Left the json examples.

I am trying to serialize this response object (request_validator) in a C# class, but this is not working. Can someone help me please, any ideas?

{
    "person": {
        "testing": "CC",
        "simple": "1234545",
        "errorNames": {
            "id": "655789",
            "error": "simple"
        },
        "errorColor": {
            "id": "2",
            "error": "error color"
        }
    }
}

{
    "request_validator": [
        {
            "person.errorNames": [
                "error names"
            ],
            "person.errorColor": [
                "error color"
            ]
        }
    ]
}

Code:

public class DeserializeResponse
{
    public Dictionary<string, List<string>> request_validator { get; set; }
}

var error = JsonConvert.DeserializeObject<List<DeserializeResponse>>(content);

Solution

  • You can use Newtonsoft.Json library to get all properties from string array into dictionary

    in this case you just need to point to the searched level

    using Newtonsoft.Json.Linq;
    ...
                JObject validator = JObject.Parse(content);
                IJEnumerable<JToken> validatorTokens = validator.SelectTokens("request_validator")?.Values();
                Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
                if (validatorTokens != null)
                {
                    foreach (JProperty prop in validatorTokens.Values())
                    {
                        if (!errors.ContainsKey(prop.Name))
                        {
                            errors.Add(prop.Name, new List<string>());
                        }
                        errors[prop.Name].Add(prop.Value?.ToString());
                    }
                }