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.

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