最近在测试通讯模块时,发现新增的Android平台发送过来的数据,服务器端总是收不到,后来发现java中数据类型有些和C#中的不一样,比如C#中byte对应范围是0~255,而Java中则对应的是-128~127,因此直接按照通讯协议传序列化的二进制流总是出现问题。考虑到这一点在Android那一端才用Joson序列化发送到服务端,而在服务端对接收到的数据进行反序列化后转化为对象。同时在服务端进行发送数据时,转换为Joson格式后,序列化为二进制流发生给Android端。
废话不多说了,上代码:
//Joson格式的二进制流转换为对象
public static T JosonDeSerializer<T>(byte[] buffer, int length)
{ try { string mTextReceived = Encoding.UTF8.GetString(buffer, 0, length);//将获取到的Joson格式字符串转换为数据包类
SocketDataPack sdp = GetSocketDataPackFromString(mTextReceived); MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter();//将数据包类序列化
formatter.Serialize(stream, sdp); stream.Position = 0; stream.Flush();//转换为对象
object obj = formatter.Deserialize(stream); if (obj == null) { return default(T); } return (T)obj; } catch (Exception ex) { throw ex; } } //对象转换为Joson格式二进制流 public static byte[] JosonSerializer(object input) { try { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); string strSocketDataPack = jsonSerializer.Serialize(input); byte[] buffer = Encoding.UTF8.GetBytes(strSocketDataPack); return buffer; } catch (Exception ex) { throw ex; } } /// <summary> /// 将Json格式的字符串转换为指定的数据包类 /// </summary> /// <param name="context"></param> /// <returns></returns> private static SocketDataPack GetSocketDataPackFromString(string context) { try { SocketDataPack sdp = new SocketDataPack(); context = context.Replace("{", "").Replace("[", "").Replace("]", "").Replace("}", "").Replace("\"", "").Replace("\0",""); String[] str = context.Split(','); for (int i = 0; i < str.Length; i++) { String[] str2 = str[i].Split(':'); switch (str2[0]) { case "Length": sdp.Length = Convert.ToInt16(str2[1]); break; case "Head": sdp.Head = Convert.ToByte(str2[1]); break; //中间的数据包类的类型省略 。。。 case "Status": sdp.Status = Convert.ToByte(str2[1]); break; case "Tail": sdp.Tail = Convert.ToByte(Convert.ToInt16(str2[1])); break; } } return sdp; } catch (Exception ex) { throw ex; } }