I suggest first convert the JSON
to model and Deserialize
the json
public class item
{
public string foo { get; set; }
public bool bar { get; set; }
}
Method 1 - using 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);
}
}
Method 2 - using LINQ
without worrying about duplicates
Dictionary<string, bool> keyValuePairs = JsonConvert.DeserializeObject<IEnumerable<item>>(json).ToDictionary(x => x.foo, x => x.bar);
Method 3 - using LINQ
by considering duplicates
Dictionary<string, bool> keyValuePairs = JsonConvert
.DeserializeObject<IEnumerable<item>>(json)
.GroupBy(p=>p.foo, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.First().foo, x => x.First().bar);
Method 4 - using 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();