JsonUtility doesn't serialize nested mixed var

I have a class:

using System;

public class GameMessage
    public string cmd;
    public object data;
    public string seedId;
    public string peerId;

    public GameMessage( string cmd, object data, string seedId = null, string peerId = null )
        this.cmd = cmd;
        this.data = data;
        this.seedId = seedId;
        this.peerId = peerId;

And in some place at the code I calling:

JsonUtility.ToJson(new GameMessage("chat/say", "hello!"));

After this operation, I don’t have data property in result JSON.
The result is: {"cmd":"chat/say","seedId":"","peerId":""}

What’s wrong? Why data doesn’t appear in final JSON structure.

data has any type. (possible string, custom object, float, array, etc…)

“object” is not serializable by Unity’s serialization system. The JsonUtility follows the same rules as the normal serialization system in Unity. The JsonUtilty is ment to extend the serialization system so you can serialize things at runtime (which wasn’t possible previously without a custom solution). It’s not ment as a general purpose Json serializer.

If you need a general purpose serializer you have to look for a custom solution like LitJson or Newtonsoft JSON.NET. Those allow mapping general objects to json and back.

Alternatively if you want a lightweight solution you can use my SimpleJSON framework. Currently it doesn’t have an automatic object mapper, but it simplifies the access and the creation of a JSON tree structure.