A good solution to use JSON into Object in C# is with JSON.NET
For converting json to list object, I used the generic deserialize method which will deserialize json into an object.
1. Create a JSON File (Here is my JSON data):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{ "Books": [ { "title": "Broken hearts", "genre": "Romance", "price": "15" }, { "title": "Nothing in my life", "genre": "Guide", "price": "12" }, { "title": "Love for love", "genre": "Romance", "price": "6" } ] } |
2. Create a Book Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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; } } |
3. Create a BookRoot Class (C# JSON to List Sample)
1 2 3 4 5 6 |
class BookRoot { public List<Book> Books { set; get; } } |
4. Create an instance of the BookRoot type and fill it using JsonConvert.DeserializeObject.
1 2 3 |
BookRoot result = JsonConvert.DeserializeObject<BookRoot>(File.ReadAllText(@"books.json")); |
5. Print JSON Data on Console Screen
1 2 3 4 5 6 7 8 9 10 11 |
Console.WriteLine("There are "+result.Books.Count+" books"); foreach (var item in result.Books) { Console.WriteLine("Book : {0}\t Genre : {1} \t Price : {2} \t", item.Title, item.Genre, item.Price); } |
This sample deserializes JSON retrieved from a file to List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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 List<Book> Books { set; get; } } class Program { static void Main(string[] args) { BookRoot result = JsonConvert.DeserializeObject<BookRoot>(File.ReadAllText(@"books.json")); Console.WriteLine("There are "+result.Books.Count+" books"); foreach (var item in result.Books) { Console.WriteLine("Book : {0}\t Genre : {1} \t Price : {2} \t", item.Title, item.Genre, item.Price); } Console.ReadLine(); } } |