Deserialize a JSON file into Dictionary Collection in C# with Newtonsoft Json library.
The Json file: (Notice: All key names must be unique)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "Books": { "Book1": { "title": "Broken hearts", "genre": "Romance", "price": "15" }, "Book2": { "title": "Nothing in my life", "genre": "Guide", "price": "12" }, "Book3": { "title": "Love for love", "genre": "Romance", "price": "6" } } } |
According to the json file, Classes would be like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Book { string title; string genre; int price; public string Title { get => title; set => title = value; } public string Genre { get => genre; set => genre = value; } public int Price { get => price; set => price = value; } public Book(string t, string g, int p) { title = t; genre = g; price = p; } } class BookRoot { public Dictionary<string, Book> Books { set; get; } } |
And Deserialize JSON data into Dictionary:
1 2 3 4 5 6 7 8 9 10 | var result = JsonConvert.DeserializeObject<BookRoot>(File.ReadAllText(@"books.json")); foreach (var item in result.Books) { Console.WriteLine("Key Name={0}", item.Key); Console.WriteLine("Book : {0}\t Genre : {1} \t Price : {2} \t", item.Value.Title, item.Value.Genre, item.Value.Price); } |