#Read JSON file (C#)?

3 messages · Page 1 of 1 (latest)

open ibex
#

Godot 4
My code so far (following a gdscript tutorial): ```csharp
private const string SavePath = "res://savegame.save";

public static void SaveGame() {
var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Write);
var data = new Dictionary {
{ "playerHP", Game.Instance.PlayerHp },
{ "Gold", Game.Instance.Gold }
};
var json = Json.Stringify(data);
file.StoreLine(json);
}

public static void LoadGame() {
if (!FileAccess.FileExists(SavePath)) {
return;
}

var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Read);
if (file.EofReached()) {
    return;
}

var currentLine = Json.ParseString(file.GetLine());
// ?

}
In gdscript, he has py

currentLine, etc already coded in C#

if current_line:
var hp = current_line["playerHP"]
var gold = current_line["gold"]
```However, in C#, I can't cast currentLine using as to a Dictionary as I get the error

Cannot convert type 'Godot.Variant' to 'Dictionary' via a built-in conversion

#

Ok, so if I direct cast, it works, but I cannot use is or as, so if the json is invalid, the program would probably error?

#

I get The given expression is never of the provided type when using is and Cannot apply operator '==' to operands of type 'Godot.Variant' and 'null' when using null