You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

36 rivejä
1.2 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.Json;
  6. using System.Text.Json.Serialization;
  7. using System.Threading.Tasks;
  8. namespace JT808.DotNetty.Core.JsonConvert
  9. {
  10. /// <summary>
  11. ///
  12. /// ref:https://github.com/dotnet/corefx/blob/release/3.0/src/System.Text.Json/tests/Serialization/CustomConverterTests.Array.cs
  13. /// </summary>
  14. public class ByteArrayHexTextJsonConverter : JsonConverter<byte[]>
  15. {
  16. public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  17. {
  18. //string hexJson = reader.get();
  19. var hexJson = reader.GetString();
  20. var list = new List<byte>();
  21. foreach (string str in hexJson.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries))
  22. {
  23. list.Add(Convert.ToByte(str, 16));
  24. }
  25. return list.ToArray();
  26. }
  27. public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
  28. {
  29. var hexString = string.Join(" ", (value).Select(p => p.ToString("X2")));
  30. writer.WriteStringValue(hexString);
  31. }
  32. }
  33. }