Vector2JsonConverter.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using Microsoft.Xna.Framework;
  5. namespace MonoGame.Extended.Serialization.Json;
  6. /// <summary>
  7. /// Converts a <see cref="Vector2"/> value to or from JSON.
  8. /// </summary>
  9. public class Vector2JsonConverter : JsonConverter<Vector2>
  10. {
  11. /// <inheritdoc />
  12. public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Vector2);
  13. /// <inheritdoc />
  14. /// <exception cref="JsonException">
  15. /// Thrown if the JSON property does not contain a properly formatted <see cref="Vector2"/> value
  16. /// </exception>
  17. public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  18. {
  19. var values = reader.ReadAsMultiDimensional<float>(options);
  20. if (values.Length == 2)
  21. {
  22. return new Vector2(values[0], values[1]);
  23. }
  24. if (values.Length == 1)
  25. {
  26. return new Vector2(values[0]);
  27. }
  28. throw new JsonException("Invalid Vector2 property value");
  29. }
  30. /// <inheritdoc />
  31. /// <exception cref="ArgumentNullException">
  32. /// Throw if <paramref name="writer"/> is <see langword="null"/>.
  33. /// </exception>
  34. public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options)
  35. {
  36. ArgumentNullException.ThrowIfNull(writer);
  37. writer.WriteStringValue($"{value.X} {value.Y}");
  38. }
  39. }