Search code examples
c#unity-game-engine

Unity DateTime is null after JsonUtility.FromJsonOverwrite


I am not so confident with Unity and C#. I have a class called UserConnect and after this line used for overwriting data inside an object

JsonUtility.FromJsonOverwrite(www.downloadHandler.text, this.userConnected);

the property datelastconnection is null, and it works only if i convert the property to string, this is how the DateTime arrives from the server

"datelastconnection":"2021-11-15 08:42:00""

namespace DataEntities
{
    [System.Serializable]
    public class UserConnect 
    {
        public string sessionid;
        public string username;
        public string img;
        public string role;
        public string firstname;
        public int iduser;
        public System.DateTime datelastconnection;

    }
}

Any idea how can i solve this issue ? my goal is to save the property of the model as DateTime and not string

should I replace this command JsonUtility.FromJsonOverwrite(www.downloadHandler.text,this.userConnected); with a custom mapper?


Solution

  • The type System.DateTime is not serializable. As a simple thumb-rule: If you cannot see it in the Inspector it is also not working with JsonUltility since they use the same Unity serializer.

    You will need a custom serialization for that part e.g. by implementing ISerializationCallbackReceiver like e.g.

    [Serializable]
    public class UserConnect : ISerializationCallbackReceiver
    {
        public string sessionid;
        public string username;
        public string img;
        public string role;
        public string firstname;
        public int iduser;
        public DateTime Datelastconnection;
    
        // serialized backing field that will actually receive the json string
        [SerializeField] private string datelastconnection;
    
        const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    
        public void OnBeforeSerialize()
        {
            // or whatever format you want to use when serializing to string
            datelastconnection = Datelastconnection.ToString(DateTimeFormat);
        }
    
        public void OnAfterDeserialize()
        {
            // after deserialization try to parse the date string into the DateTime field
            DateTime.TryParseExact(datelastconnection, DateTimeFormat, out Datelastconnection);
        }
    }