The GetFromJsonAsync method can be used to read data from a JSON text 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.
Update: According to Yong Shun's response, if only the data in the "student" JSON header is needed, it may be sufficient to create only the Student and the Root classes:
@code {
private Student[]? students;
protected override async Task OnInitializedAsync()
{
Root? root = await Http.GetFromJsonAsync<Root>("school.json");
students = root.Student.ToArray();
}
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("student")]
public List<Student>? Student { get; set; }
}
}