如何将具有不同 JSON 结构的 JSON 数组解析为 List
本文关键字:JSON List string 数组 结构 | 更新日期: 2023-09-27 18:34:36
我找到的所有解决方案都不满意,因为我没有相同的JSON结构。我的 JSON 数组:
string str = @"[{
"type": "text",
"field": [
"tags",
"track_title"
],
"value": "hero",
"operation": "must"
}, {
"type": "range",
"field": "duration",
"value": [
0,
5
],
"operation": "must"
}, {
"type": "range",
"field": "duration",
"value": [
180,
null
],
"operation": "must"
}]"
如您所见,JSON 是不同的。所以我不能使用特定的模型类通过它进行转换。我需要接收带有单独 JSON 的List<string>
。我该如何解析它?
根据我的理解,我建议我们手动执行此操作。这是代码:
string str = @"[{
'type': 'text',
'field': [
'tags',
'track_title'
],
'value': 'hero',
'operation': 'must'
}, {
'type': 'range',
'field': 'duration',
'value': [
0,
5
],
'operation': 'must'
}, {
'type': 'range',
'field': 'duration',
'value': [
180,
null
],
'operation': 'must'
}]";
// Remove 2 brackets []
str = str.Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
// Split string
string[] delimiter = {"},"};
string[] data = str.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
// The list you want
List<string> result = new List<string>();
// Turn the array into List with some modification
foreach (string s in data)
{
string tmp = s;
if (!s.EndsWith("}"))
{
tmp = s + "}";
}
result.Add(tmp.Trim());
}
// Display data
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
代码是自我解释的。如果您发现不清楚的地方,请告诉我。
基本上,
您可以做的是将 Json 反序列化为动态类型,以便它可以处理差异。例如,这里有如何使用 Json.Net 库来做到这一点