How to serialize and deserialize Vector2 using C#?
Asked Answered
G

4

0

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.

Groot answered 9/3, 2023 at 23:42 Comment(0)
I
0

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 ?

Impossibly answered 10/3, 2023 at 15:18 Comment(0)
G
0

Impossibly 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.

Groot answered 10/3, 2023 at 21:42 Comment(0)
B
0

Groot 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!

Buccaneer answered 18/12, 2023 at 4:46 Comment(0)
B
0

Buccaneer To answer my question, looks like this is what I would need to do: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-8-0#registration-sample---converters-collection

but i ended up just using Newtonsoft.Json library as it seems to serialize Vector3 without an issue

Buccaneer answered 18/12, 2023 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.