Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
1k views
in Programming by 20 36 42
edited by

I have an employee's data in json file as shown below, and I need to retrive just the first and last name attributes from this JSON file using C#, How can I read this json file contents in C#?

[
 {
   “FirstName” = “khaled”,
    “LastName” = “alomar”,
     “Age” = 30
 },
 {
   “FirstName” = “Mohammed”,
    “LastName” = “saleh”,
     “Age” = 35
 },
  {
   “FirstName” = “Fatima”,
    “LastName” = “Nasser”,
     “Age” = 26
 }
]

 


1 Answer

0 like 0 dislike
by 20 36 42
edited by

Read from JSON file in C#

To read from a json file, you have to do the following:

  1. You need first to create a instance of a StreamReader to read from a text file.
  2. You should have the file path, and then you can use the ReadToEnd method to read all file contents.
  3. Finally, you have to use JsonConvert.DeserializeObject method to deserialize the JSON to the .NET type.

     using Newtonsoft.Json;
     var data = new List<string>();
      using( StreamReader sr = new StreamReader(“data.json”)){
         string json = sr.ReadToEnd();
         data = JsonConvert.DeserializeObject<List<string >>(json);
      }
    

Note: You have to add the namespace Newtonsoft.Json

If you don’t ask, the answer is always NO!
...