You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
2.1 KiB

  1. using IPA.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Runtime.CompilerServices;
  6. using System.Text.Json;
  7. using System.Text.Json.Nodes;
  8. using System.Text.Json.Serialization;
  9. namespace IPA.JsonConverters
  10. {
  11. internal class FeaturesFieldConverter : JsonConverter<Dictionary<string, List<JsonObject>>>
  12. {
  13. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  14. private static void Assert([DoesNotReturnIf(false)] bool condition)
  15. {
  16. if (!condition)
  17. throw new InvalidOperationException();
  18. }
  19. public override Dictionary<string, List<JsonObject>> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  20. {
  21. if (reader.TokenType == JsonTokenType.StartArray)
  22. {
  23. // TODO: Why?
  24. _ = JsonSerializer.Deserialize<string[]>(ref reader, options);
  25. Logger.Features.Warn("Encountered old features used. They no longer do anything, please move to the new format.");
  26. // TODO: Is there an alternative to existingValue?
  27. return null;
  28. }
  29. var dict = new Dictionary<string, List<JsonObject>>();
  30. Assert(reader.TokenType == JsonTokenType.StartObject && reader.Read());
  31. while (reader.TokenType == JsonTokenType.PropertyName)
  32. {
  33. var name = reader.GetString();
  34. Assert(reader.Read());
  35. var list = reader.TokenType == JsonTokenType.StartObject
  36. ? (new() { JsonSerializer.Deserialize<JsonObject>(ref reader, options) })
  37. : JsonSerializer.Deserialize<List<JsonObject>>(ref reader, options);
  38. dict.Add(name, list);
  39. Assert(reader.Read());
  40. }
  41. return dict;
  42. }
  43. public override void Write(Utf8JsonWriter writer, Dictionary<string, List<JsonObject>> value, JsonSerializerOptions options)
  44. {
  45. JsonSerializer.Serialize(writer, value, options);
  46. }
  47. }
  48. }