Search code examples
c#jsonconvert

C# Deserialize Object


I have a web socket on my server and that sockets return list of player infos to the all clients. After I get the data from websocket ı cant deserilialize my data cause c# adding some '"' characters to my data. And ı cant remove that characters

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

My Json string in debug mode look like this. How can i clear this string and deserialize. I have this class in my project property names and everything okey ı just need the get rid of \ character and " character at the beginning and end of data.

  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; }
    }

And this is my class

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.

On Client side I get the byte array from socket and convert string like this

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

than deserilialize like this

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

This is data in text visualizer
This is data in text visualizer
Thanks for your help.


Solution

  • Just try this:

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