Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

JSON Serializing problem

Discussion in 'Editor & General Support' started by Smurfj3, Oct 14, 2019.

  1. Smurfj3


    Feb 15, 2015
    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:

    Code (CSharp):
    1.  [Serializable]
    2.     public class AnimData
    3.     {
    4.         public int id;
    5.         public int type;
    6.         public bool dirty;
    7.         public float Value;    
    8. }
    10. //I use the following line to serialize
    12. 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
  2. JasonBricco


    Jul 15, 2013
    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.
    Code (CSharp):
    1. [Serializable]
    2. public class Data
    3. {
    4.     public List<AnimData> data;
    5. }