Unity C# JsonUtility is not serializing a list Unity C# JsonUtility is not serializing a list json json

Unity C# JsonUtility is not serializing a list


There are 4 known possible reasons why you may get empty Json in Unity.

1.Not including [Serializable]. You get empty json if you don't include this.

2.Using property (get/set) as your variable. JsonUtility does not support this.

3.Trying to serializing a collection other than List.

4.Your json is multi array which JsonUtility does not support and needs a wrapper to work.

The problem looks like #1. You are missing [Serializable] on the the classes. You must add using System; in order to use that.

[Serializable]public class SpriteData {    public string sprite_name;    public Vector2 sprite_size;    public List<Vector2> subimage;}

and

[Serializable]public class SpriteDataCollection{    public SpriteData[] sprites;}

5.Like the example, given above in the SpriteData class, the variable must be a public variable. If it is a private variable, add [SerializeField] at the top of it.

[Serializable]public class SpriteDataCollection{    [SerializeField]    private SpriteData[] sprites;}

If still not working then your json is probably invalid. Read "4.TROUBLESHOOTING JsonUtility" from the answer in the "Serialize and Deserialize Json and Json Array in Unity" post. That should give you inside on how to fix this.


One other cause Programmer didn't mention but is a big stickler:

[Serializable]public struct MyObject{    public string someField;}[Serializable]public class MyCollection{    public readonly List<MyObject> myObjects = new List<MyObject>();    //     ^-- BAD}

A list won't serialize if it is using readonly. E.g.

MyCollection collection = new MyCollection();collection.myObjects.Add(new MyObject {someField = "Test"});string json = JsonUtility.ToJson(collection);// {}


Unity3D has an old-fashioned Json library. You can use the Newtonsoft.Json, a standard JSON library in .NET ecosystem. However, it doesn't support Unity3D and you need to get the specialized package for Unity3D. You can get it from its Github or from the Unity Asset Store.

using Newtonsoft.Json;    ...    ...The_Object the_object = new The_Object(...);....string jsonString = JsonConvert.SerializeObject(the_object);The_Oobject deserialized_object = JsonConvert.DeserializeObject<The_Object>(jsonString);

Please note that SerializableAttribute should be applied on The_Object class and any used object type inside it. Also, you have to indicate variables that you want to parse by json as public.For example:

[Serializable]class first_class{    public second_class sceond = new second_class();    public System.Collections.Generic.List<List<third_class>> third_nested_list;    //....}[Serializable]class second_class{    public third_class third = new third_class();    //....}[Serializable]class third_class{    public string name;    //....}