【发布时间】:2018-09-07 06:18:34
【问题描述】:
我正在做一个项目,我想将 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。
我哪里出错了,解决办法是什么?
【问题讨论】:
-
问题是数组中的字典。
-
我需要键值对或字典
-
@skhurams 你需要什么是无关紧要的。 JSON 是一个对象数组。所以至少你的代码需要是字典的集合
-
你能把它转换成数组,这样我就可以得到键和值
-
您在问题中发布的错误消息可以准确地告诉您问题所在。将您的反序列化更改为
Dictionary<string, string>的集合(列表、数组等)