0

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?

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
  • This is the Item class ```public class Item { public string controlable; public List commands; public List objects; public struct Object { public string symbol; public ObjectPosition position; } public struct ObjectPosition { public int x; public int y; } }``` – Muhammad Khalish Zhafran May 13 '23 at 04:36
  • But your classes are using fields not properties, and System.Text.Json.JsonSerializer does not support fields by default. Change then to properties by adding `{get; set; }` e.g. `public List commands { get; set; }` as shown in [this answer by Serge to .Net System.Text.Json cannot serialize object](https://stackoverflow.com/a/70161744), or enable field support as shown in [How to use class fields with System.Text.Json.JsonSerializer?](https://stackoverflow.com/q/58139759). – dbc May 13 '23 at 04:39
  • (You may have other problems aside from using fields, it's hard to tell from the comment.) – dbc May 13 '23 at 04:41

0 Answers0