我正在做一个项目,我想将 json 数据转换为字典,但问题是 json 是非同质的。我正在使用 newtonsoft.json
这是JSON:
[{
'_type': 'StatsItem',
'Noofpostcomments': 0,
'URL': 'https: //www.website.com/',
'posts': 1,
'Brand': 'Halfords',
'Likes': 24884,
'movedTo': 'FB',
'sharing': 0,
'talked': 94,
'following': '24757',
'Date': '27-Mar-2018',
'unpopular': 0,
'ID': '2453'
},
{
'_type': 'StatsItem',
'qualify': 53,
'URL': 'https: //www.website.com/',
'post': 3,
'Brand': 'Kwik',
'Likes': 32339,
'movedTo': 'FB',
'share': 128,
'talk': 542,
'followers': '31824',
'Date': '27-Mar-2018',
'bands': 240,
'ID': '2453'
},
{
'_type': 'StatsItem',
'luck': 0,
'URL': 'https: //www.website.com/',
'bites': 0,
'Brand': 'SEAT',
'likes': 5329114,
'movedTo': 'FB',
'shares': 0,
'talking': 552,
'Followers': '5300000',
'Date': '27-Mar-2018',
'bands': 0,
'ID': '2453'
},
{
'_type': 'StatsItem',
'spoofs': 1,
'URL': 'https: //www.website.com/',
'security': 1,
'Brand': 'Honda',
'fixes': 184065,
'movedTo': 'FB',
'shares': 15,
'chat': 4251,
'follow': null,
'Date': '27-Mar-2018',
'discussed': 102,
'ID': '2453'
}]
这是代码:
Dictionary<string, string> columnDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
也试过
JObject result = JObject.Parse(jsonString);
它给出了例外
Newtonsoft.Json.dll 中发生类型为“Newtonsoft.Json.JsonSerializationException”的未处理异常
附加信息:无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“System.Collections.Generic.Dictionary`2[System.String,System.String]”,因为该类型需要 JSON 对象(例如{"name":"value"}) 正确反序列化。
要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。JsonArrayAttribute 也可以添加到类型以强制它从 JSON 数组反序列化。
路径 '',第 1 行,位置 1。
我哪里出错了,解决方法是什么?
您可以将其解析为字典的数组(或列表): List<Dictionary<string, object>>
var list = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonData);
foreach(var item in list)
{
foreach(KeyValuePair<string, object> keyVal in item)
{
Console.WriteLine($"{keyVal.Key}: {keyVal.Value?.ToString()}");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句