- Home /
The question is answered, right answer was accepted
,Cannot deserialize object of class from imported library by json.net
,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 using JSON.NET. 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}]"}
Resolved by deleting getters, setters on public variable: public Ws$$anonymous$$essageType type { get; set; } public string data { get; set; }
change to: public Ws$$anonymous$$essageType type; public string data;
So, there are 3 points need to take attention when make serialization of object from 3rd party library when using IL2CPP: 1. No getters/setters 2. All public fields also must be [Serializable], like Ws$$anonymous$$essageType in my case 3. Class must have default constructor without parameters.
Answer by Bunny83 · Jul 15, 2020 at 11:16 AM
IL2CPP is an AOT platform (ahead of time compilation) so no dynamic code generations is possible on an AOT platform. There are modified forks of the original newtonsoft json.net that should work on AOT platforms. I have never used it but it's worth a try.
Answer by a88236 · Jul 15, 2020 at 12:56 PM
Bunny83, thank you for your answer, but actually i am already use this version of json.net (re-installed again for sure, but no result). Also, as i mentioned, object deserializing normally when i moving class directly to Unity project, but not when this class locating in library.
Possibly, my library WebSocketModels not compiling for AOT. Is there some special requirements how to import library for AOT platform?
Follow this Question
Related Questions
C# JSON library 6 Answers
Install JsonFX 1 Answer
minijson pars 0 Answers
3D dynamic map generation 0 Answers