Godot 4 C# Convert Godot.Variant to Dictionary<string, object>

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By raviolicheddar


So i am trying to load a JSON file stored in my resource as a Dictionary of string and objects in C#. Here is my code so far :

using var file = FileAccess.Open("res://Datas/fileName.json", FileAccess.ModeFlags.Read);
string content = file.GetAsText();
var jsonObject = new JSON();
var error = jsonObject.Parse(content);
if(error == Error.Ok)
	Variant dataReceived = jsonObject.Data;
	// Line bellow result in an error
	Dictionary<string, object> dataReceivedAsDictionary = jsonObject.Data as Dictionary<string, object>;

jsonObject.Data always returns a Variant.

My issue is that I can not convert the type Godot.Variant in System.Collections.Generic.Dictionary<string, object>. When logged in console, dataReceived seems to return a string, and its type to always be Godot.Variant.

I’ve tried using GD.Convert but it returns the same exact Variant type value…
I’ve also tried converting dataCompiled as a Godot.Collections.Dictionary instead of just a Dictionary, as specified on a thread with the exact same question using Godot 3.x, and end up with the same result : cannot convert the type Godot Variant in Godot.Collections.Dictionary.

All of the examples on internet provide outdated for Godot4 (such as the File class that doesn’t seems to exist anymore, replaced with FileAccess).

jsonObject.Data as Dictionary<string, object>;

Errors because it is not a generic dictionary, it’s the Godot dictionary. You could manually add each element to a generic dictionary if you want, or just use the Godot dictionary.

That said, as you’re using C#, why not just use the framework JSON parser or Newtonsoft.Json?

spaceyjase | 2023-01-20 12:42

:bust_in_silhouette: Reply From: juppi


like spaceyjase already mentioned, you can use another Json (De)Serializer.
Either Newtonsoft or the build in of .NET:

Just use the Godot FileAccess to read and write the Content as String.

Thanks for your reply, this is what I ended up doing :slight_smile:

raviolicheddar | 2023-01-22 19:19