首页 前端知识 C#中Socket通讯时接收到数据后通过Json反序列化时出现异常:“0x00 is invalid after a single JSON value. Expected...“

C#中Socket通讯时接收到数据后通过Json反序列化时出现异常:“0x00 is invalid after a single JSON value. Expected...“

2024-09-14 23:09:46 前端知识 前端哥 835 233 我要收藏

1. 问题描述

(1)Send时将List<PlatenInfo>数据通过Json序列化成string类型,并通过Socket发送。
string recipeInfo = JsonSerializer.Serialize<List<PlatenInfo>>(wafer.RecipeInfo);
var recipeData = Encoding.UTF8.GetBytes(recipeInfo);
_acceptSocket.Send(recipeData);
(2)接收端Receive数据后,通过Json反序列化成List<PlatenInfo>数据。
try
{
    byte[] buffer = new byte[1024];     //Receive数据时要先指定读取字节长度
    _tcpClient.Receive(buffer);
    string msg = Encoding.UTF8.GetString(buffer);
    List<PlatenInfo>? list = JsonSerializer.Deserialize<List<PlatenInfo>>(msg);
}
catch (Exception ex)
{
    Log(ex.Message);
}
在反序列化的时候发生异常:

2. 问题分析

Socket将接收到的数据放到设定了1024字节大小的buffer中,buffer前有部分是有效的信息,后半段是空白\0符号。只有前半部分才可以反序列化成想要的结果,而整个操作的话就异常了。

3. 问题解决:

可以去除尾部0x00空白区域。

如果像上述字符编码的,则可以在接收到data并转换为string后,再直接加上:

msg = msg.TrimEnd('\0');        //将最后的0x00空白区域去掉

便可以反序列化成功。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/18288.html
标签
c#
评论
发布的文章

关于HTML的知识

2024-09-18 23:09:36

js简单实现轮播图效果

2024-09-18 23:09:36

CSS3美化网页元素

2024-09-18 23:09:27

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!