xvlv
xvlv
CC#
Created by xvlv on 5/12/2024 in #help
Easiest way to serialize System.Numerics.Vector3 using System.Text.Json (.NET 8)
I'm writing a 3D level editor in .NET and OpenGL and need level data to be stored as human-readable text, so I'm using System.Text.Json. Since Vector3 exposes its data as fields instead of properties, it always gets serialized as {}:
using System.Numerics;
using System.Text.Json;

string json = JsonSerializer.Serialize(new Vector3(1, 2, 3));
Console.WriteLine(json); // Prints {}
using System.Numerics;
using System.Text.Json;

string json = JsonSerializer.Serialize(new Vector3(1, 2, 3));
Console.WriteLine(json); // Prints {}
I wrote this custom converter that writes the value as "1,2,3":
// Usings omitted for brevity...

JsonSerializerOptions options = new() { Converters = { new JsonVector3Converter() } };
string json = JsonSerializer.Serialize(new Vector3(1, 2, 3), options);
Console.WriteLine(json);

internal sealed class JsonVector3Converter : JsonConverter<Vector3>
{
public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string? token = reader.GetString();
// Parsing code omitted for brevity...

return new Vector3(x, y, z);
}

public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
{
// Omitted for brevity...
// string x =

writer.WriteStringValue($"{x},{y},{z}");
}
}
// Usings omitted for brevity...

JsonSerializerOptions options = new() { Converters = { new JsonVector3Converter() } };
string json = JsonSerializer.Serialize(new Vector3(1, 2, 3), options);
Console.WriteLine(json);

internal sealed class JsonVector3Converter : JsonConverter<Vector3>
{
public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string? token = reader.GetString();
// Parsing code omitted for brevity...

return new Vector3(x, y, z);
}

public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
{
// Omitted for brevity...
// string x =

writer.WriteStringValue($"{x},{y},{z}");
}
}
I'm curious if this is the recommended approach or is there's an easier way to do the same thing (besides using Newtonsoft). Has anyone else implemented anything similar? Wanted to ask here before I implement custom converters for Vector2, Quaternion, etc.
3 replies