[英]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);
您可以使用 Newtonsoft.Json 库将字符串数组中的所有属性放入字典
在这种情况下,您只需要指向搜索的级别
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.