From 1d8a4e1459ac81f39db3a1038ce3f4473cfbcb31 Mon Sep 17 00:00:00 2001 From: andy840119 Date: Mon, 21 Feb 2022 20:50:48 +0800 Subject: [PATCH] implement base sortable class. --- .../Converters/SortableJsonConvertor.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 osu.Game.Rulesets.Karaoke/IO/Serialization/Converters/SortableJsonConvertor.cs diff --git a/osu.Game.Rulesets.Karaoke/IO/Serialization/Converters/SortableJsonConvertor.cs b/osu.Game.Rulesets.Karaoke/IO/Serialization/Converters/SortableJsonConvertor.cs new file mode 100644 index 000000000..1f939e6ae --- /dev/null +++ b/osu.Game.Rulesets.Karaoke/IO/Serialization/Converters/SortableJsonConvertor.cs @@ -0,0 +1,38 @@ +// Copyright (c) andy840119 . Licensed under the GPL Licence. +// See the LICENCE file in the repository root for full licence text. + +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace osu.Game.Rulesets.Karaoke.IO.Serialization.Converters +{ + public abstract class SortableJsonConvertor : JsonConverter> + { + public sealed override IEnumerable ReadJson(JsonReader reader, Type objectType, IEnumerable existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var obj = JArray.Load(reader); + var timeTags = obj.Select(x => serializer.Deserialize(x.CreateReader())); + return GetSortedValue(timeTags); + } + + public override void WriteJson(JsonWriter writer, IEnumerable value, JsonSerializer serializer) + { + // see: https://stackoverflow.com/questions/3330989/order-of-serialized-fields-using-json-net + var sortedTimeTags = GetSortedValue(value); + + writer.WriteStartArray(); + + foreach (var timeTag in sortedTimeTags) + { + serializer.Serialize(writer, timeTag); + } + + writer.WriteEndArray(); + } + + protected abstract IEnumerable GetSortedValue(IEnumerable objects); + } +}