C# Cannot deserialize object of class from imported library

265 Views Asked by At

In Unity project I have some class WsMessage for WebSocket interaction. This class located in my own library WebSocketModels.

namespace WebSocketModels
{
    [Serializable]
    public enum WsMessageType 
    { 
        System, Player, Challenge, DeclineChallenge, RemoveChallenge, Game, Move, Moves, Chat,
        Players, Challenges, Games, Clock                        
    }    
    
    [Serializable]
    public class WsMessage
    {
        public WsMessageType type { get; set; }
        public string data { get; set; }

        public WsMessage() { }

        public WsMessage(WsMessageType type, string data)
        {
            this.type = type;
            this.data = data;
        }
    }
}

By some reason it cannot be deserialized. I didn't see any errors. If i move this class from library directly to Unity project object of WsMessage creating normally. I use this simple command for get an object of WsMessage:

WsMessage message = JsonConvert.DeserializeObject<WsMessage>(inputWsMessage);

I've met this problem after change my Unity player Scripting Backend to IL2CPP. On Mono everything was OK.

Example of JSON content

{"type":10,"data":"[{\"id\":\"0d8648e4-ce15-4084-87f9-f3de2b5a9b32\",\"fromPlayer\":{\"id\":\"af76e7c3-27b2-4d05-bcd3-f4b41c3bb7ba\",\"name\":\"Aydar\",\"rating\":1600.0,\"isOnline\":false},\"color\":0,\"timeControl\":{\"time_range\":10,\"time_increment\":5,\"control_type\":0},\"toPlayer\":null}]"}
1

There are 1 best solutions below

0
On BEST ANSWER

So, seems like the problem is here;

public WsMessageType type { get; set; }
public string data { get; set; }

Why? because { get; set; } is syntactic sugar for getter and setter methods.

So, in other words, your code above is 'equivalent' to;

public void WsMessageType_SetValue(WsMessageType value)
{
    WsMessageType = value;    
}

public WsMessageType WsMessageType_GetValue()
{
    return WsMessageType;
}

And the same for 'data'.

The problem arises when you try to serialize some data into some function, it doesn't make it sense, and the { get; set; } shortcut makes it harder to see.

If you use variables instead of getter/setter it should work!

ie;

public WsMessageType type;
public string data;