Sorry I'm new to both C# and Godot.
I want to save the player's position in file. I use JsonSerializer.Serialize to convert struct into string.

struct Player {
    public string name { get; set; }
    public Vector2I position { get; set; }
}

name can be serialized correctly, but position can't.
So how can I store Vector2 in file ?

Or should split position into X and Y ?
I know it works, but it's really cumbersome, it's the last approach I want to use.

my first thought was that youre using namespace godot and the serializer doesnt know godot. and Vector2I seems to be godot. so first i think you should use System.Numerics.Vector2 from C#. but i tried and with that it seems not to work too - so it is not problem of godot. i think its problem of the serialiser ?

    systemerror Actually, I asked a stupid question.
    I'm just trying to convert a custom data structure to a string, so it's definitely not a Godot problem. But as I said, I'm new to both Godot and C#, so after searching for half an hour and not finding anything, I came here for help.
    Usually most programming languages expose virtual methods for conversion if they have a Convert library, so then I searched for virtual methods for JsonSerialization Convert and implemented it myself.

    public class Vector2IJsonConverter : JsonConverter<Vector2I>
    {
        public override Vector2I Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
        {
            return (Vector2I)GD.StrToVar(reader.GetString()!);
        }
    
        public override void Write(
            Utf8JsonWriter writer,
            Vector2I vector2iValue,
            JsonSerializerOptions options)
        {
            writer.WriteStringValue(GD.VarToStr(vector2iValue));
        }
    }

    Everything worked as expected now.

    • olgo replied to this.
      9 months later

      CrayonApe I'd like to do something like this for Vector3. I copied your class and converted it to Vector3, how do i ensure JsonSerializer uses it for that class? Thanks!

      • olgo replied to this.