JSON Serializing problem

Hello there,

I am having trouble using the JsonUtility.ToJson function. The answers I find online are confusing, I am trying to serialize a List of a custom type, which is a plain class that only includes int, bool and float. All of the variables are public and the class has an Serializable attribute. On the Unity docs I see it says “passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none).” To me it looks like that a list woulnd’t work either however I have read about people using this to serialize a list so I am very confused right now. This is the code:

 [Serializable]
    public class AnimData
    {
        public int id;
        public int type;
        public bool dirty;
        public float Value;    
}

//I use the following line to serialize

string data = JsonUtility.ToJson(DataList);

On Debug.Log it show the string data as “{}”, I am a 100 percent sure the list contains items, I have a debug right before the serializing to check for the list count.

Thanks in advance

You can’t pass a list directly to the ToJson() method, just like with arrays.

All you have to do is put the list in a wrapper class and serialize that class.

[Serializable]
public class Data
{
    public List<AnimData> data;
}