very newbie programmer here trying to learn C#. I’m trying to deserialise a JSON file and then print the values inside. However, I’m met with a Jsonexception in the form of cannot be converted to the class I made.
The code in question:
public class Games
{
public string? Title { get; set;}
public int ReleaseYear { get; set;}
public double Rating { get; set;}
}
public class ReadAndParseJSONFromFile()
{
public static void ReadingJSON()
{
string filePath = @"C:UsersKodainC#Game Data Parsergames.json";
string jsonString = File.ReadAllText(filePath);
Games games = JsonSerializer.Deserialize<Games>(jsonString)!;
System.Console.WriteLine("Loaded games are: ");
System.Console.WriteLine($"{games.Title}, released in {games.ReleaseYear}, rating: {games.Rating}");
}
}
and the provided JSON file:
[
{
"Title": "Stardew Valley",
"ReleaseYear": 2016,
"Rating": 4.9
},
{
"Title": "Frostpunk",
"ReleaseYear": 2017,
"Rating": 4.7
},
{
"Title": "Oxygen Not Included",
"ReleaseYear": 2017,
"Rating": 4.8
},
{
"Title": "Red Dead Redemtpion II",
"ReleaseYear": 2018,
"Rating": 4.8
},
{
"Title": "Portal 2",
"ReleaseYear": 2011,
"Rating": 4.8
}
]
I tried to use the Microsoft documentation on how to deserialise since I’ve never done it before with JSON, only text files. I expected the program to read the JSON file, then print out all the games with title, release year, and rating. Instead I got a Jsonexception that tells me that the JSON value cannot be converted to Games:
Exception has occurred: CLR/System.Text.Json.JsonException
An unhandled exception of type ‘System.Text.Json.JsonException’ occurred in System.Text.Json.dll: ‘The JSON value could not be converted to Games.’
I tried my google-fu, but I too much of a noob and cannot seem to find a solution to my problem. I am quite stumped.
C L is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.