using System; using System.Collections.Generic; using System.Linq; namespace Newtonsoft.Json { /// /// Converts a byte array from and to a hex string. /// [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public class ByteArrayHexConverter : JsonConverter { /// /// List of known types to use this converver. /// public static readonly Type[] KnownTypes = [ typeof(byte[]), typeof(List), typeof(IEnumerable) ]; /// public override bool CanConvert(Type objectType) => KnownTypes.Contains(objectType); /// public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) return null; string hex = (string)reader.Value; var byteEnum = hex.HexToBytes(); if (typeof(byte[]) == objectType) return byteEnum.ToArray(); if (typeof(List) == objectType) return byteEnum.ToList(); return byteEnum; } /// public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { string hex = null; if (value == null) { writer.WriteValue(hex); return; } if (value is byte[] byteArray) hex = byteArray.BytesToHex(); if (value is List byteList) hex = byteList.BytesToHex(); if (value is IEnumerable byteEnum) hex = byteEnum.BytesToHex(); writer.WriteValue(hex); } } }