1
0
forked from liza/Questionable
Questionable/Questionable.Model/V1/Converter/VectorConverter.cs

65 lines
1.9 KiB
C#
Raw Normal View History

2024-05-26 19:45:26 +00:00
using System;
using System.Numerics;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Questionable.Model.V1.Converter;
2024-06-14 09:37:33 +00:00
public sealed class VectorConverter : JsonConverter<Vector3>
2024-05-26 19:45:26 +00:00
{
public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
throw new JsonException();
Vector3 vec = new Vector3();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.PropertyName:
string? propertyName = reader.GetString();
if (propertyName == null || !reader.Read())
throw new JsonException();
switch (propertyName)
{
case nameof(Vector3.X):
vec.X = reader.GetSingle();
break;
case nameof(Vector3.Y):
vec.Y = reader.GetSingle();
break;
case nameof(Vector3.Z):
vec.Z = reader.GetSingle();
break;
default:
throw new JsonException();
}
break;
case JsonTokenType.EndObject:
return vec;
default:
throw new JsonException();
}
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteNumber(nameof(Vector3.X), value.X);
writer.WriteNumber(nameof(Vector3.Y), value.X);
writer.WriteNumber(nameof(Vector3.Z), value.X);
writer.WriteEndObject();
}
}