Hello, first off, I’d like to say that I have read everything I can find on the subject of the limitations of JsonUtility and have seen similar threads with solutions that simply don’t work for me. I am also unable to get any other json library such as Newtonsoft.json to work. This is for a game mod and so I am not working in the Unity editor, just visual studio.
I’m trying to make a small save system using Json and would like to be able to serialize a custom serializable class. Ultimately, I will need a list of these, but I’m just trying to get a single instance working first.
Here is my code structure:
[Serializable]
public class SaveList
{
// I have some ints, strings, and float values here that work fine
public PartColor partColor;
}
[Serializable]
public class PartColor
{
public int partNum;
public float r;
public float g;
public float b;
public float a;
public PartColor(int partNum, Color col)
{
this.partNum = partNum;
r = col.r;
g = col.g;
b = col.b;
a = col.a;
}
}
I call JsonUtility.ToJson() from another Monobehavior class on a SaveList object and all I get is “{ }”.
Note: If I add Monobehavior to the PartColor class, I do get an output, its just in the format { “m_FileID”: 0,“m_PathID”: 0 }" which is unusable to me.
Any help would be greatly appreciated.
EDIT
I decided to go with XML serialization instead given the limitations of Unity’s Json library. Thanks for the help.
You would need to provide a default ctor() for PartColor otherwise the JSON utility has no idea how to make one. It relies on that default ctor() existing because it cannot know about your <int,Color> ctor(); and how to feed it properly.
Beyond that, I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.
Instead grab Newtonsoft JSON .NET off the asset store for free, as it is way better.
PS: for folks howling about how it will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.
Well, like I said, this is for a mod and I cannot get an external dll library to work, I have tried Newtonsoft.Json and litJson with no luck. I also added a default constructor to the class and I get the same results. Thanks for replying though.
Yes, I am positive that it is not null, I even have a check for that. I am loading the mod via UnityModManager. The mod itself works fine and I have a simple save/load system already that writes plain text to file. I just wanted a cleaner solution.