TcModelConverter.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Newtonsoft.Json;
  2. using System.Text;
  3. namespace AmrControl.ADS
  4. {
  5. /// <summary>
  6. /// TcModel的JSON转换器
  7. /// 这个是把byte[]与ASCII字符串互转
  8. /// </summary>
  9. public class TcModelArrayConverter : JsonConverter
  10. {
  11. public override bool CanConvert(Type objectType)
  12. {
  13. return objectType == typeof(byte[]);
  14. }
  15. /// <summary>
  16. /// 把json字符串转对象
  17. /// </summary>
  18. /// <param name="reader"></param>
  19. /// <param name="objectType"></param>
  20. /// <param name="existingValue"></param>
  21. /// <param name="serializer"></param>
  22. /// <returns></returns>
  23. /// <exception cref="NotImplementedException"></exception>
  24. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  25. {
  26. //todo,需要评估一下长度有没有影响,在结构体中限定了长度
  27. string str = (string)reader.Value;
  28. if(str == null)
  29. {
  30. //返回一个空数组
  31. //return new byte[12];
  32. return null;
  33. }
  34. else
  35. {
  36. //byte[] chars = Encoding.ASCII.GetBytes(str);
  37. //byte[] bytes = new byte[12];
  38. //if(chars.Length <= 12)
  39. //{
  40. // Array.Copy(chars, bytes, chars.Length);
  41. //}
  42. //else
  43. //{
  44. // Array.Copy(chars, bytes, 12);
  45. //}
  46. //return bytes;
  47. return Encoding.ASCII.GetBytes(str);
  48. }
  49. }
  50. /// <summary>
  51. /// 把对象转json字符串
  52. /// </summary>
  53. /// <param name="writer"></param>
  54. /// <param name="Data"></param>
  55. /// <param name="serializer"></param>
  56. /// <exception cref="NotImplementedException"></exception>
  57. public override void WriteJson(JsonWriter writer, object? Data, JsonSerializer serializer)
  58. {
  59. if(Data is byte[] bytes)
  60. {
  61. //判断非0的长度,0是字符串结尾
  62. int index = 0;
  63. for (int i = 0; i < bytes.Length; i++)
  64. {
  65. if (bytes[index++] == 0)
  66. {
  67. break;
  68. }
  69. }
  70. writer.WriteValue(Encoding.ASCII.GetString(bytes,0,index).Trim());
  71. }
  72. }
  73. }
  74. }