我建议先转换JSON
为模型和Deserialize
json
public class item
{
public string foo { get; set; }
public bool bar { get; set; }
}
方法 1 - 使用foreach
using (StreamReader r = new StreamReader(filepath))
{
string json = r.ReadToEnd();
var obj = JsonConvert.DeserializeObject<List<item>>(json);
Dictionary<string, bool> keyValuePairs = new Dictionary<string, bool>();
foreach (var keyvalue in obj)
{
if (!keyValuePairs.ContainsKey(keyvalue.foo))
keyValuePairs.Add(keyvalue.foo, keyvalue.bar);
}
}
方法二——LINQ
不用担心重复使用
Dictionary<string, bool> keyValuePairs = JsonConvert.DeserializeObject<IEnumerable<item>>(json).ToDictionary(x => x.foo, x => x.bar);
方法 3 -LINQ
通过考虑重复使用
Dictionary<string, bool> keyValuePairs = JsonConvert
.DeserializeObject<IEnumerable<item>>(json)
.GroupBy(p=>p.foo, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.First().foo, x => x.First().bar);
方法 4 - 使用DeserializeAnonymousType
var definition = new[] {new { foo = "", bar = false } };
string json = @"[{'foo': '1', 'bar': false}, {'foo': '2', 'bar': true}]";
var obj = JsonConvert.DeserializeAnonymousType(json, definition).Select(p=> (p.foo, p.bar)).ToList();