简体   繁体   中英

Serialize Json object with properties dinamycally 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 someone who can 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"
            ]
        }
    ]
}

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

}

var error = JsonConvert.DeserializeObject<List<DeserializeResponse>>(content);
public class DeserializeResponse
{
    [JsonPropertyName("request_validator")]
    public RequestValidator[] RequestValidator { get; set; }
}

public class RequestValidator
{
    [JsonPropertyName("person.errorNames")]
    public string[] PersonErrorNames { get; set; }

    [JsonPropertyName("person.errorColor")]
    public string[] PersonErrorColor { get; set; }
}

...

var error = JsonSerializer.Deserialize<DeserializeResponse>(content);

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());
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM