1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using Newtonsoft.Json;
- using System.Text;
- namespace AmrControl.ADS
- {
- /// <summary>
- /// TcModel的JSON转换器
- /// 这个是把byte[]与ASCII字符串互转
- /// </summary>
- public class TcModelArrayConverter : JsonConverter
- {
- public override bool CanConvert(Type objectType)
- {
- return objectType == typeof(byte[]);
- }
- /// <summary>
- /// 把json字符串转对象
- /// </summary>
- /// <param name="reader"></param>
- /// <param name="objectType"></param>
- /// <param name="existingValue"></param>
- /// <param name="serializer"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
- {
-
- //todo,需要评估一下长度有没有影响,在结构体中限定了长度
- string str = (string)reader.Value;
- if(str == null)
- {
- //返回一个空数组
- //return new byte[12];
- return null;
- }
- else
- {
- //byte[] chars = Encoding.ASCII.GetBytes(str);
- //byte[] bytes = new byte[12];
- //if(chars.Length <= 12)
- //{
- // Array.Copy(chars, bytes, chars.Length);
- //}
- //else
- //{
- // Array.Copy(chars, bytes, 12);
- //}
- //return bytes;
- return Encoding.ASCII.GetBytes(str);
- }
- }
- /// <summary>
- /// 把对象转json字符串
- /// </summary>
- /// <param name="writer"></param>
- /// <param name="Data"></param>
- /// <param name="serializer"></param>
- /// <exception cref="NotImplementedException"></exception>
- public override void WriteJson(JsonWriter writer, object? Data, JsonSerializer serializer)
- {
- if(Data is byte[] bytes)
- {
- //判断非0的长度,0是字符串结尾
- int index = 0;
- for (int i = 0; i < bytes.Length; i++)
- {
- if (bytes[index++] == 0)
- {
- break;
- }
- }
- writer.WriteValue(Encoding.ASCII.GetString(bytes,0,index).Trim());
- }
- }
- }
- }
|