C# 反序列化对象

问题描述

我的服务器上有一个网络套接字,该套接字将玩家信息列表返回给所有客户端。从 websocket 获取数据后,我无法反序列化我的数据,导致 c# 在我的数据中添加了一些 '"' 字符。我无法删除这些字符

"\"[{\\\"Id\\\":\\\"\\\",\\\"Location\\\":{\\\"X\\\":60.0,\\\"Y\\\":60.0,\\\"Z\\\":10.0},\\\"Rotation\\\":{\\\"X\\\":10.0,\\\"Y\\\":10.0,\\\"State\\\":\\\"walk\\\",\\\"IsAttacking\\\":false,\\\"PlayerName\\\":\\\"Sadooo\\\",\\\"Health\\\":100,\\\"LastSync\\\":637598981481744771}]\""

我在调试模式下的 Json 字符串如下所示。我怎样才能清除这个字符串并反序列化。 我的项目属性名称中有这个类,一切都好,我只需要在数据的开头和结尾去掉 \ 字符和 " 字符。

  public class PlayerInfo
    {
        //public string IpAdress { get; set; }
        public string Id { get; set; }
        public MyVector Location { get; set; }
        public MyVector Rotation { get; set; }
        public string State { get; set; }
        public bool IsAttacking { get; set; }
        public string PlayerName { get; set; }
        public int Health { get; set; }
        public long LastSync { get; set; }

    }
    public class MyVector
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Z { get; set; }
    }

这是我的班级

JsonConvert.SerializeObject(myList);//This is how i serilaized  to my data. After that I convert this string to byte array and send to the socket.

在客户端 我从套接字获取字节数组并像这样转换字符串

var data=Encoding.UTF8.GetString(result.Buffer);

像这样反序列化

 var players= JsonConvert.DeserializeObject<List<PlayerInfo>>(data,new JsonSerializerSettings { NullValueHandling=NullValueHandling.Ignore});

This is data in text visualizer


这是文本可视化工具中的数据
感谢您的帮助。

解决方法

试试这个:

var players= JsonConvert.DeserializeObject<List<PlayerInfo>>(
JsonConvert.DeserializeObject<string>(data),new JsonSerializerSettings { NullValueHandling=NullValueHandling.Ignore});
,

它显然看起来像是多级序列化,看起来您正在将对象序列化为 json 字符串,然后再将其传递给 websocket 库,然后将其序列化为字符串。

在这种情况下,尝试多级反序列化或删除不必要的序列化。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...