Json.ParseString(json).As() doesn't properly read "Variant" and defaults to null

Godot Version

v4.3.stable.mono.official [77dcf97d8]

Question

I made a save system which uses the following data structure to save information:

{
  "intro_entrance": {
    "4602dff7-4067-4622-8ca3-a2d262f58006": {
      "HasBeenActivatedAtLeastOnce": true,
      "IsEnabled": false,
      "TimesTriggered": 1
    },
    "5c819875-7f44-4cf4-b581-ae3533c81e9d": {
      "HasBeenActivatedAtLeastOnce": false,
      "IsEnabled": true,
      "TimesTriggered": 0
    },
    "96d2893f-187b-45f2-9812-5af1e4a4381a": {
      "ActiveState": "PlayerIdleState",
      "FacingLeft": false,
      "GlobalPosition": "(2159.828, 303.924)",
      "Velocity": "(0, 0)"
    }
  }
}

And it works great while I keep this entire structure in memory and play around with it, loading works as well.

This JSON was saved from the following variable:

SaveInfo.Data = new Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, Variant>>>();

Saving it works perfectly with string data = Json.Stringify(SaveInfo.Data, fullPrecision: true); as you can see from the snippet of JSON above.

However, my problem is with loading this same file. Loading it with the following line:

SaveInfo.Data = Json.ParseString(json).As<Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, Godot.Collections.Dictionary<string, Variant>>>>();

This gives me no exceptions, and will set the data seemingly properly, with the only exception that the Variants deep in the Dictionary will ALWAYS be null no matter what. The same thing happens if I use Newtonsofts json.

Am I doing something wrong here?

The problem was two fold.

I decided to modify my Dictionary so even at the very end, I save things as string.
However, this still didn’t work, turns out here’s the correct way to turn Variants into strings, then back:

Turn variant into string:

GD.VarToStr(GlobalPosition)

Turn said string back into variant, and the correct type. You need to know what that type is though!

Vector2 pos = GD.StrToVar(globalPosition).AsVector2();

This worked flawlessly for me.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.