Search code examples
c#jsonblazorblazor-webassembly

Blazor - Retrieve the data under the header of a specified JSON file


The GetFromJsonAsync method can be used to read data from a JSON file into a variable in a Blazor web application. The method works well for simple JSON files.

Example for GetFromJsonAsync method:

@code {
    private Students[]? students;

    protected override async Task OnInitializedAsync()
    {
        students = await Http.GetFromJsonAsync<Students[]>("school.json");
    }

    public class Students
    {
        public int id { get; set; }

        public string? name { get; set; }

        public string? lastname { get; set; }

    }
}

My question is, how can I read only the data in a given JSON header?

Example:

{
  "book":[
     {
        "id":"444",
        "language":"C",
        "edition":"First",
        "author":"Dennis Ritchie "
     },
     {
        "id":"555",
        "language":"C++",
        "edition":"second",
        "author":" Bjarne Stroustrup "
     }
  ],
  "student": [ 
     { 
        "id":"01", 
        "name": "Tom", 
        "lastname": "Price" 
     }, 
     { 
        "id":"02", 
        "name": "Nick", 
        "lastname": "Thameson" 
     } 
  ]     
}

I only would like to read the data under the "student" JSON header into a students variable.


Solution

  • You need a Root class. And suggest naming the property names as Pascal case and using the JsonPropertyName attribute

    public class Book
    {
        [JsonPropertyName("id")]
        public string Id { get; set; }
    
        [JsonPropertyName("language")]
        public string Language { get; set; }
    
        [JsonPropertyName("edition")]
        public string Edition { get; set; }
    
        [JsonPropertyName("author")]
        public string Author { get; set; }
    }
    
    public class Student
    {
        [JsonPropertyName("id")]
        public string Id { get; set; }
    
        [JsonPropertyName("name")]
        public string Name { get; set; }
    
        [JsonPropertyName("lastname")]
        public string Lastname { get; set; }
    }
    
    public class Root
    {
        [JsonPropertyName("book")]
        public List<Book> Book { get; set; }
    
        [JsonPropertyName("student")]
        public List<Student> Student { get; set; }
    }
    

    Deserialize the JSON as Root object.

    protected override async Task OnInitializedAsync()
    {
       Root root = await Http.GetFromJsonAsync<Root>("school.json");
       students = root.Students;
    }