I want to read a json file and parse it to C# attributes, but I got some errors like this
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
This is my code:
public class Program
{
public static void Main(string[] args)
{
Item item = FileReader.Read<Item>("Levels/Level1.json");
foreach (string command in item.commands)
{
Console.WriteLine(command);
}
}
}
public class Item
{
public string controlable;
public List<string> commands;
public List<Object> objects;
public struct Object
{
public string symbol;
public ObjectPosition position;
}
public struct ObjectPosition
{
public int x;
public int y;
}
}
using System.Text.Json;
public class FileReader
{
public static T Read<T>(string fileName)
{
string text = File.ReadAllText(fileName);
return JsonSerializer.Deserialize<T>(text);
}
}
{
"controlable": "R",
"commands": ["Forward", "Backward"],
"objects": [
{
"symbol": "B",
"position": {
"x": 3,
"y": 5
}
}
]
}
The attributes not set from json file, is it error coz I don't use asyncronous? how to fix it?