![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | Dostoi |
TL;DR: How to convert a parsed json string to a godot.Collections.Dictionary? In other words, why this returns a “null” value?
var dict = JSON.Parse(savedGame.GetAsText()).Result as Godot.Collections.Dictionary;
Detailed version: All the variables in my game are stored in a single dictionary that looks like that:
gamevariables = new Godot.Collections.Dictionary
{
{ "variable_A", false},
{ "variable_B", false},
{ "variable_etc", true}
}
I can then successfuly store these value to a text file like that:
var savedData = _gameVariables.gamevariables.ToString();
var savedGame = new File();
savedGame.Open("user://save_example_slot_1.save", File.ModeFlags.Write);
savedGame.StoreLine(JSON.Print(savedData));
savedGame.Close();
This correctly creates the file containing the following text:
"{variable_A:False, variable_B:False, variable_etc:True}"
And now, where the troubles begin. What I’m trying to do is basicaly overwrite the base dictionary named “gamevariables” in this example, by the one that I saved (with variables which might have different value from before). So I do that:
var savedGame = new File();
savedGame.Open("user://save_example_slot_1.save, File.ModeFlags.Read);
JSONParseResult dict = JSON.Parse(savedGame.GetAsText());
savedGame.Close();
And if I add:
GD.Print(_gameVariables.gamevariables);
GD.Print(dict.Result);
It returns the exact same structures of text:
{variable_A:False, variable_B:False, variable_etc:True}
{variable_A:False, variable_B:False, variable_etc:True}
Yet, they are of different types as the next experiment proves:
GD.Print(_gameVariables.gamevariables.GetType());
GD.Print(dict.Result.GetType());
Which returns:
Godot.Collections.Dictionary
System.String
But since they have the same structure, I though it would be possible to cast the System.String one as a Godot.Collections.Dictionary. So here’s what I did:
var dict2 = dict.Result as Godot.Collections.Dictionary;
which doesn’t works since it returns “null”. Moreover, which indicates that the conversion, somehow, failed, trying to returns a value from “GD.Print(dict2.GetType());” crashes the game. Which, I think, indicate some sort of “invalid” type.
So, what am I misunderstanding to be able to load a string of text stored in a text file as a dictionary?
Thank you for your time.
https://www.youtube.com/watch?v=g_7hgbxjtLY
Landroval | 2023-02-12 16:26