- Home /
JsonUtility doesn't serialize nested mixed var
I have a class:
using System;
[Serializable]
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...)
Answer by Bunny83 · Sep 18, 2017 at 11:18 PM
"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.
Sounds great. But I need the solution which will work on all supported by Unity platforms.
Your answer
Follow this Question
Related Questions
How to protect JSON file game data? 3 Answers
Unity json get data 2 Answers
Is it possible to executing object serialization into JSON asynchronously? 1 Answer
JsonUtility array not supported? 7 Answers