1
0
Files
common/AMWD.Common/Converters/ByteArrayHexConverter.cs

71 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace Newtonsoft.Json
{
/// <summary>
/// Converts a byte array from and to a hex string.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class ByteArrayHexConverter : JsonConverter
{
/// <summary>
/// List of known types to use this converver.
/// </summary>
public static readonly Type[] KnownTypes = new[]
{
typeof(byte[]),
typeof(List<byte>),
typeof(IEnumerable<byte>)
};
/// <inheritdoc/>
public override bool CanConvert(Type objectType)
{
return KnownTypes.Contains(objectType);
}
/// <inheritdoc/>
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<byte>) == objectType)
return byteEnum.ToList();
return byteEnum;
}
/// <inheritdoc/>
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<byte> byteList)
hex = byteList.BytesToHex();
if (value is IEnumerable<byte> byteEnum)
hex = byteEnum.BytesToHex();
writer.WriteValue(hex);
}
}
}