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.

53 lines
2.0 KiB

  1. using IPA.Logging;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics.CodeAnalysis;
  7. using System.Runtime.CompilerServices;
  8. namespace IPA.JsonConverters
  9. {
  10. internal class FeaturesFieldConverter : JsonConverter<Dictionary<string, List<JObject>>>
  11. {
  12. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. private static void Assert([DoesNotReturnIf(false)] bool condition)
  14. {
  15. if (!condition)
  16. throw new InvalidOperationException();
  17. }
  18. public override Dictionary<string, List<JObject>> ReadJson(JsonReader reader, Type objectType, Dictionary<string, List<JObject>> existingValue, bool hasExistingValue, JsonSerializer serializer)
  19. {
  20. if (reader.TokenType == JsonToken.StartArray)
  21. {
  22. _ = serializer.Deserialize<string[]>(reader);
  23. Logger.features.Warn("Encountered old features used. They no longer do anything, please move to the new format.");
  24. return existingValue;
  25. }
  26. var dict = new Dictionary<string, List<JObject>>();
  27. Assert(reader.TokenType == JsonToken.StartObject && reader.Read());
  28. while (reader.TokenType == JsonToken.PropertyName)
  29. {
  30. var name = (string)reader.Value;
  31. Assert(reader.Read());
  32. var list = reader.TokenType == JsonToken.StartObject
  33. ? (new() { serializer.Deserialize<JObject>(reader) })
  34. : serializer.Deserialize<List<JObject>>(reader);
  35. dict.Add(name, list);
  36. Assert(reader.Read());
  37. }
  38. return dict;
  39. }
  40. public override void WriteJson(JsonWriter writer, Dictionary<string, List<JObject>> value, JsonSerializer serializer)
  41. {
  42. serializer.Serialize(writer, value);
  43. }
  44. }
  45. }