With reading a JSON object, you will need to have your JSON data. You can either read in a string, or read a file into a string. Here we have some sample data:
[
{
"category": "HISTORY",
"air_date": "2004-12-31",
"question": "'For the last 8 years of his life, Galileo was under house arrest for espousing this man's theory'",
"value": "200",
"answer": "Copernicus",
"round": "Jeopardy!",
"show_number": "4680"
},
{
"category": "ESPN's TOP 10 ALL-TIME ATHLETES",
"air_date": "2004-12-31",
"question": "'No. 2: 1912 Olympian; football star at Carlisle Indian School; 6 MLB seasons with the Reds, Giants & Braves'",
"value": "200",
"answer": "Jim Thorpe",
"round": "Jeopardy!",
"show_number": "4680"
},
{
"category": "EVERYBODY TALKS ABOUT IT...",
"air_date": "2004-12-31",
"question": "'The city of Yuma in this state has a record average of 4,055 hours of sunshine each year'",
"value": "200",
"answer": "Arizona",
"round": "Jeopardy!",
"show_number": "4680"
},
{
"category": "THE COMPANY LINE",
"air_date": "2004-12-31",
"question": "'In 1963, live on \"The Art Linkletter Show\", this company served its billionth burger'",
"value": "200",
"answer": "McDonald's",
"round": "Jeopardy!",
"show_number": "4680"
}
]
This minor sample came from a much larger file set: https://domohelp.domo.com/hc/en-us/articles/360043931814-Fun-Sample-DataSets
Then we need to have a class which we can use to read in the data.
class JeopardyQuestion
{
public string category { get; set; }
public string airDate { get; set; }
public string question { get; set; }
public int value { get; set; }
public string answer { get; set; }
public string round { get; set; }
public int show_number { get; set; }
public JeopardyQuestion()
{
}
public JeopardyQuestion(string category, string airDate, string question,
int value, string answer, string round, int show_number)
{
this.category = category;
this.airDate = airDate;
this.question = question;
this.value = value;
this.answer = answer;
this.round = round;
this.show_number = show_number;
}
}
This information is fairly simple for this example. We could of course have much more complicated data if necessary.
Note: The JSON deserialize function will want a default (no-arg) constructor.
Now, inside our function where we’re going to read the data, we will load the data:
System.Console.WriteLine("Now to read in the data...");
string json = File.ReadAllText("jeapordy.json");
Note: We will have to import (use) using System.IO; to access File, and System.Text.Json to get the JSON library.
And then load the JSON data.
JeopardyQuestion[] questions = JsonSerializer.Deserialize<JeopardyQuestion[]>(json);
Of course, once you import the data, you should do something with it:
for(int i = 0; i < questions.Length; i++)
{
Console.WriteLine("Q: " + questions[i].question);
Console.WriteLine("A: " + questions[i].answer);
Console.WriteLine();
}
Working with JSON – Reading a Data File was originally found on Access 2 Learn