-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0ea897b
commit 1d8a4e1
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
osu.Game.Rulesets.Karaoke/IO/Serialization/Converters/SortableJsonConvertor.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
// Copyright (c) andy840119 <[email protected]>. 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<TObject> : JsonConverter<IEnumerable<TObject>> | ||
{ | ||
public sealed override IEnumerable<TObject> ReadJson(JsonReader reader, Type objectType, IEnumerable<TObject> existingValue, bool hasExistingValue, JsonSerializer serializer) | ||
{ | ||
var obj = JArray.Load(reader); | ||
var timeTags = obj.Select(x => serializer.Deserialize<TObject>(x.CreateReader())); | ||
return GetSortedValue(timeTags); | ||
} | ||
|
||
public override void WriteJson(JsonWriter writer, IEnumerable<TObject> 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<TObject> GetSortedValue(IEnumerable<TObject> objects); | ||
} | ||
} |