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?

3
  • This is the Item class 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; } } Commented May 13, 2023 at 4: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<string> commands { get; set; } as shown in this answer by Serge to .Net System.Text.Json cannot serialize object, or enable field support as shown in How to use class fields with System.Text.Json.JsonSerializer?. Commented May 13, 2023 at 4:39
  • (You may have other problems aside from using fields, it's hard to tell from the comment.) Commented May 13, 2023 at 4:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.