From a6f3a497b435fd0699f49b767c3d42e1b3d55de5 Mon Sep 17 00:00:00 2001 From: Crsky Date: Wed, 16 Jul 2025 03:53:21 +0800 Subject: [PATCH] Add FormatCatalog.SerializeSchemeJson --- GameRes/FormatCatalog.cs | 71 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/GameRes/FormatCatalog.cs b/GameRes/FormatCatalog.cs index 98354db2..6b6f0335 100644 --- a/GameRes/FormatCatalog.cs +++ b/GameRes/FormatCatalog.cs @@ -33,6 +33,9 @@ using GameRes.Collections; using System.Runtime.Serialization.Formatters.Binary; using GameRes.Compression; using System.Threading; +using System.Text; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; namespace GameRes { @@ -389,6 +392,74 @@ namespace GameRes } } + class IncludeFieldsContractResolver : DefaultContractResolver + { + protected override JsonContract CreateContract (Type objectType) + { + var contract = base.CreateContract (objectType); + + if (contract is JsonObjectContract objectContract) + { + objectContract.MemberSerialization = MemberSerialization.Fields; + } + + return contract; + } + } + + class ByteArrayToHexStringConverter : JsonConverter + { + public override byte[] ReadJson (JsonReader reader, Type objectType, byte[] existingValue, bool hasExistingValue, JsonSerializer serializer) + { + throw new NotImplementedException (); + } + + public override void WriteJson (JsonWriter writer, byte[] value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull (); + return; + } + var s = ByteArrayToString (value); + writer.WriteValue (s); + } + + private static string ByteArrayToString (byte[] input) + { + var sb = new StringBuilder (input.Length * 2); + foreach (var b in input) + sb.AppendFormat ("{0:X2}", b); + return sb.ToString (); + } + } + + public void SerializeSchemeJson (Stream output) + { + var db = new SchemeDataBase + { + Version = CurrentSchemeVersion, + SchemeMap = new Dictionary (), + GameMap = m_game_map, + }; + foreach (var format in Formats) + { + var scheme = format.Scheme; + if (null != scheme) + db.SchemeMap[format.Tag] = scheme; + } + var settings = new JsonSerializerSettings + { + ContractResolver = new IncludeFieldsContractResolver (), + Converters = { new ByteArrayToHexStringConverter () }, + Formatting = Formatting.Indented, + }; + var json = JsonConvert.SerializeObject (db, settings); + var sw = new StreamWriter (output, Encoding.UTF8); + sw.Write (json); + sw.Flush (); + } + /// /// Read text file from data directory, performing action on each non-empty line. ///