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.

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

and

Copy[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.

Copy[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.

Answer from Programmer on Stack Overflow
🌐
Unity
discussions.unity.com › questions & answers
[SOLVED] Converting a Generic List to JSON in Unity - Questions & Answers - Unity Discussions
June 4, 2017 - Hello programmers, I am a beginner and I searched and tried some solutions, but it didn’t fit / solved my case. I guess this is simple, but I didn’t came to an answer yet. Hope you guys could help me. Ok, I have this Class and Object for a 2D Tile Map creator: public class Columns { public int[] lines; } public Columns[] tilesMap; After putting some numbers to the ‘int’ lists I wanted to save it as a .JSON.
Top answer
1 of 5
51

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.

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

and

Copy[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.

Copy[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.

2 of 5
4

I know this post is old.. However, I recently had a similar problem to the question here. To clarify...

Using JsonUtility, if you have a List of a "serializable" class, JsonUtility will return an Empty response.

Copy[Serializable]
public class SomeSerializableClass
{
     public SomeSerializableClassB instance = new();
}

[Serializable]
public class SomeSerializableClassB
{
     public int x = 123;
}

public class Something{
    public List<SomeSerializableClass> collection = new();

    public string GetJson()
    {
         return JsonUtility.ToJson(collection);
    }
}

GetJson() here will return nothing. Instead, wrap the List collection into another class, then it will serialize and convert correctly.

Copy[Serializable]
public class SomeSerializableClassList
{
    public List<SomeSerializableClass> instances = new();
}

[Serializable]
public class SomeSerializableClass
{
     public SomeSerializableClassB instance = new();
}

[Serializable]
public class SomeSerializableClassB
{
     public int x = 123;
}

public class Something{
    public SomeSerializableClassList collection = new();

    public string GetJson()
    {
         return JsonUtility.ToJson(collection);
    }
}

Its difficult to comprehend why this doesn't work when you read "Lists are supported". Maybe someone smarter than me can explain...

Discussions

[SOLVED] Converting a Generic List to JSON in Unity - Questions & Answers - Unity Discussions
Hello programmers, I am a beginner and I searched and tried some solutions, but it didn’t fit / solved my case. I guess this is simple, but I didn’t came to an answer yet. Hope you guys could help me. Ok, I have this Class and Object for a 2D Tile Map creator: public class Columns { public ... More on answers.unity.com
🌐 answers.unity.com
0
June 4, 2017
List array to json file / makes objects with parsed json file
This is the whole code? First of all: public List LectureDB = new List(); this is List. You're using List not Array List. I'm only claryfyng, because if you say stuff and it's something else communication is really hard. I don't mind, only pointing out because maybe you don't use C# or use other language or not use any and we have some language noise problem. then in Start you have two loops that is setting elements of this LectureDB: for (int i= 0; i<4; i++) { for(int j=0; j<12; j++) { LectureDB[(i * 12 + j)].LecName = "major" + ((i * 12) + (j + 1)); LectureDB[i * 12 + j].LecYear = i + 1; LectureDB[i * 12 + j].lecType = LecType.Major; LectureDB[i * 12 + j].IsSignUp = false; LectureDB[i * 12 + j].LecCredit = 3; } } for(int i=0; i<5; i++) { LectureDB[48 + i].LecName = "PreRequisite" + (48+i); LectureDB[48 + i].LecYear = 1; LectureDB[48 + i].lecType = LecType.PreRequisite; LectureDB[48 + i].IsSignUp = false; LectureDB[48 + i].LecCredit = 2; } for (int i = 0; i < 30; i++) { LectureDB[53 + i].LecName = "Elective" + (53+i); LectureDB[53 + i].LecYear = 1; LectureDB[53 + i].lecType = LecType.Elective; LectureDB[53 + i].IsSignUp = false; LectureDB[53 + i].LecCredit = 2; } But how does elements of the LectureDB gets to the list. I assume you assign them manually in inspector? or do you have some other code that you didn't show. List AllLectureList = LectureDB; string json = JsonUtility.ToJson(AllLectureList); Debug.Log(json); It shows nothing because probably LectureDB is nothing. So you assigning nothing to AllLectureList , and then try to convert nothing to string json which ends up with nothing showed as a debug. That's defenitely what's happening. But we still don't have any clue why. I'm still confused how you set up LectureDB elements. Can you send printscreen from Inspector if you set elements by it, or code where you Add Lecture to the List? That's where the issue really is but you didn't show it. More on reddit.com
🌐 r/Unity3D
2
0
December 15, 2022
JsonUtilities.ToJson with List not working as expected - Unity Engine - Unity Discussions
Hi guys, I’m trying to serialize a list using JsonUtilities.ToJson, however I’m running into a problem When I do the above, the string that it returns is just " {} " I don’t understand why it’s returning object, as far as I am aware, ToJson should serialize lists no problem. More on discussions.unity.com
🌐 discussions.unity.com
1
August 5, 2019
unity - How can I serialize lists to JSON on mobile? - Game Development Stack Exchange
I'm having difficulties serializing lists with the built in JsonUtility. I eventually figured out this just isn't possible with its limited capabilities. As much as I'd like to use Newtonsoft, I ca... More on gamedev.stackexchange.com
🌐 gamedev.stackexchange.com
🌐
Unity
discussions.unity.com › unity engine
Export data from List to .json file - Unity Engine - Unity Discussions
August 3, 2020 - I am working on a simple AR 3d scanner project, and as a beginning I am trying to reconstruct a 3d model from a list of recorded point cloud data. I am kind of new to unity scripting and don’t actually know how I can con…
🌐
Reddit
reddit.com › r/unity3d › list array to json file / makes objects with parsed json file
r/Unity3D on Reddit: List array to json file / makes objects with parsed json file
December 15, 2022 -

hi guys.

I'm korean college student.

I'm sorry about my dirty codes to see you.

I have problem with unity.

I want changing my List array to json file.

And parsing json file, and create objects with that.

So, I write some code, and run it.

but doesn't make json file.

---------------------------

string json = JsonUtility.ToJson(AllLectureList);

Debug.Log(json);

--------------------------

console only say

-------------------

{}

unityEngine.Debug.log(object)

there are belows my whole code

<LecDatabase.cs>

using System.Collections;

using System.Collections.Generic;

using System.Data.SqlTypes;

using UnityEngine;

using UnityEngine.SocialPlatforms;

using System.IO;

[System.Serializable]

public class LecDatabase : MonoBehaviour

{

public static LecDatabase lecDatabase;

public int Credit;

private void Awake()

{

lecDatabase = this;

}

public List<Lecture> LectureDB = new List<Lecture>();

public GameObject LecItemPrefab;

public Vector3[] pos;

private void Start()

{

for (int i= 0; i<4; i++)

{

for(int j=0; j<12; j++)

{

LectureDB[(i * 12 + j)].LecName = "major" + ((i * 12) + (j + 1));

LectureDB[i * 12 + j].LecYear = i + 1;

LectureDB[i * 12 + j].lecType = LecType.Major;

LectureDB[i * 12 + j].IsSignUp = false;

LectureDB[i * 12 + j].LecCredit = 3;

}

}

for(int i=0; i<5; i++)

{

LectureDB[48 + i].LecName = "PreRequisite" + (48+i);

LectureDB[48 + i].LecYear = 1;

LectureDB[48 + i].lecType = LecType.PreRequisite;

LectureDB[48 + i].IsSignUp = false;

LectureDB[48 + i].LecCredit = 2;

}

for (int i = 0; i < 30; i++)

{

LectureDB[53 + i].LecName = "Elective" + (53+i);

LectureDB[53 + i].LecYear = 1;

LectureDB[53 + i].lecType = LecType.Elective;

LectureDB[53 + i].IsSignUp = false;

LectureDB[53 + i].LecCredit = 2;

}

List<Lecture> AllLectureList = LectureDB;

string json = JsonUtility.ToJson(AllLectureList);

Debug.Log(json);

Credit = 0;

}

}

<Lectures.cs>

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

[System.Serializable]

public enum LecType

{

Major,

PreRequisite,

Elective

}

[System.Serializable]

public class Lecture

{

public LecType lecType;

public string LecName;

public int LecCredit;

public int LecYear;

public bool IsSignUp;

}

Top answer
1 of 2
2
This is the whole code? First of all: public List LectureDB = new List(); this is List. You're using List not Array List. I'm only claryfyng, because if you say stuff and it's something else communication is really hard. I don't mind, only pointing out because maybe you don't use C# or use other language or not use any and we have some language noise problem. then in Start you have two loops that is setting elements of this LectureDB: for (int i= 0; i<4; i++) { for(int j=0; j<12; j++) { LectureDB[(i * 12 + j)].LecName = "major" + ((i * 12) + (j + 1)); LectureDB[i * 12 + j].LecYear = i + 1; LectureDB[i * 12 + j].lecType = LecType.Major; LectureDB[i * 12 + j].IsSignUp = false; LectureDB[i * 12 + j].LecCredit = 3; } } for(int i=0; i<5; i++) { LectureDB[48 + i].LecName = "PreRequisite" + (48+i); LectureDB[48 + i].LecYear = 1; LectureDB[48 + i].lecType = LecType.PreRequisite; LectureDB[48 + i].IsSignUp = false; LectureDB[48 + i].LecCredit = 2; } for (int i = 0; i < 30; i++) { LectureDB[53 + i].LecName = "Elective" + (53+i); LectureDB[53 + i].LecYear = 1; LectureDB[53 + i].lecType = LecType.Elective; LectureDB[53 + i].IsSignUp = false; LectureDB[53 + i].LecCredit = 2; } But how does elements of the LectureDB gets to the list. I assume you assign them manually in inspector? or do you have some other code that you didn't show. List AllLectureList = LectureDB; string json = JsonUtility.ToJson(AllLectureList); Debug.Log(json); It shows nothing because probably LectureDB is nothing. So you assigning nothing to AllLectureList , and then try to convert nothing to string json which ends up with nothing showed as a debug. That's defenitely what's happening. But we still don't have any clue why. I'm still confused how you set up LectureDB elements. Can you send printscreen from Inspector if you set elements by it, or code where you Add Lecture to the List? That's where the issue really is but you didn't show it.
2 of 2
1
So factoring Unity's limitations of its implementation, here's the way serialization with JSON works in Unity : - You can't serialize arrays or lists directly. You have to wrap it inside a class. - Then, the list's and the wrapper's output type must be a Serializable class, but you've already done that so it's great. Yeah basically everything has to be Serializable for it to work. It's tricky, but once you stick to that I'm sure you'll get the hang of it! To try and circumvent these limitations, I wrote some neat Dictionary and List extensions. You can check them if you'd like : https://github.com/bodardr/utility/blob/a1a48e0aa5d423a903f8d514fcec263ecb440500/Runtime/Scripts/DictionaryExtensions.cs they won't help you solve your problem directly, but it helps with deserializing Dictionaries and lists when Unity falls short... If you have the time after your assignment, here's more info on how Unity serializes everything. From prefabs to components in the inspector to scenes, absolutely everything : https://docs.unity3d.com/Manual/script-Serialization.html#bestPractise
🌐
Unity
docs.unity3d.com › ScriptReference › JsonUtility.ToJson.html
Unity - Scripting API: JsonUtility.ToJson
You should not alter the object that you pass to this function while it is still executing. Additional resources: MonoBehaviour, ScriptableObject, Object.GetInstanceID · using UnityEngine; public class PlayerState : MonoBehaviour { public string playerName; public int lives; public float health; public string SaveToString() { return JsonUtility.ToJson(this); } // Given: // playerName = "Dr Charles" // lives = 3 // health = 0.8f // SaveToString returns: // {"playerName":"Dr Charles","lives":3,"health":0.8} }
🌐
Unity
discussions.unity.com › unity engine
JsonUtilities.ToJson with List not working as expected - Unity Engine - Unity Discussions
August 5, 2019 - Hi guys, I’m trying to serialize a list using JsonUtilities.ToJson, however I’m running into a problem When I do the above, the string that it returns is just " {} " I don’t understand why it’s returning object, as fa…
Find elsewhere
🌐
YouTube
youtube.com › watch
Storing Data (Objects & Lists) with JSON - Unity Tutorial 2021 - YouTube
In this tutorial you'll learn how to save and read data into JSON files. We focuse more on lists which needs a little bit more code than default objects, but...
Published   May 17, 2021
🌐
Reddit
reddit.com › r/unity3d › using the new jsonutility in 5.4 how do you serialize a list?
r/Unity3D on Reddit: Using the new JsonUtility in 5.4 how do you serialize a List<>?
October 6, 2016 -

Upto now I've been using the older 5.3 way of converting a List of objects into a very, very long string and serializing that. But I've recently found out the builtin JsonUtility can now work with arrays?

I'm new to this but I'm struggling to do this as simple as possible ;0

For the record I'm trying to create a 3d tile loading and saving system so its a bunch of world xyz etc and Tiletype.

Top answer
1 of 1
2

You can't serialize a List<> directly, same with a top-level array; you need a data container object. See below for an example, just put this script on an empty GameObject in your scene and press Play:

using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Demonstration of generic List serialization using JsonUtility
/// </summary>
public class ListTest : MonoBehaviour
{
	/// <summary>
	/// Initialization
	/// </summary>
	void Start ()
	{
		string json = SerializeToJson();
		DeserializeFromJson(json);
	}


	/// <summary>
	/// Creates the list and serializes it to a Json string
	/// </summary>
	/// <returns>Serialized Json string</returns>
	string SerializeToJson()
	{
		List<SomeDataModel> dataList = new List<SomeDataModel>();

		dataList.Add(new SomeDataModel(0, "Entry 1"));
		dataList.Add(new SomeDataModel(1, "Entry 2"));
		dataList.Add(new SomeDataModel(2, "Entry 3"));

		ListContainer container = new ListContainer(dataList);

		// TODO: Wrap this in try/catch to handle serialization exceptions
		string json = JsonUtility.ToJson(container);

		// Outputs: {"dataList":[{"ID":0,"Name":"Entry 1"},{"ID":1,"Name":"Entry 2"},{"ID":2,"Name":"Entry 3"}]}
		Debug.Log(json);

		return json;
	}


	/// <summary>
	/// Deserializes the Json string into the list object
	/// </summary>
	/// <param name="json">Json string</param>
	void DeserializeFromJson(string json)
	{
		// TODO: Wrap this in try/catch to handle deserialization exceptions
		ListContainer container = JsonUtility.FromJson<ListContainer>(json);

		Debug.Log(container.dataList.Count);
		for (int i = 0; i < container.dataList.Count; i++)
		{
			Debug.Log("ID: " + container.dataList[i].ID + ", Name: " + container.dataList[i].Name);
		}
	}
}


/// <summary>
/// Container struct for the List
/// </summary>
public struct ListContainer
{
	public List<SomeDataModel> dataList;

    /// <summary>
	/// Constructor
	/// </summary>
	/// <param name="_dataList">Data list value</param>
	public ListContainer(List<SomeDataModel> _dataList)
	{
		dataList = _dataList;
	}
}


/// <summary>
/// Some generic data model, used for List entries
/// </summary>
[Serializable]
public struct SomeDataModel
{
	public int ID;
	public string Name;

	/// <summary>
	/// Constructor
	/// </summary>
	/// <param name="_ID">ID value</param>
	/// <param name="_Name">Name value</param>
	public SomeDataModel(int _ID, string _Name)
	{
		ID = _ID;
		Name = _Name;
	}
}
🌐
Unity
discussions.unity.com › unity engine
Importing lists of custom objects from JSON - Unity Engine - Unity Discussions
June 14, 2023 - I’m trying to store my game data in JSON files, but I can’t get my loader to properly load it. I’ve been looking at examples, but I can’t see anything wrong with my code. void ImportJSON() { Object[] areaObjects = Resources.LoadAll("Areas",typeof(TextAsset)); //This loading works, I get all the objects as files foreach(Object data in areaObjects) { string JSONstring = data.ToString(); AreaListObject newAreaData = JsonUtility.FromJson
🌐
Unity
forum.unity.com › unity engine
Json utility - save and load a list - Unity Engine - Unity Discussions
August 15, 2017 - As the title says. If I have a class: public class MyList { public List class; } How can I check if a json file exists, and if not create one? And then how can I load this list, and save it when I need to? I’ve re…
🌐
Unity
discussions.unity.com › questions & answers
Writing List as Json ,Making a List in Json - Questions & Answers - Unity Discussions
October 15, 2022 - Trying to write a string array inside a List in the Json format, have been trying my best but i’ve been getting a bug saying that the list is null, pretty sure it’s the way i’m writing my Json as the script bugging is literally Texts.Count; Currently writing the List as: "AppearanceTexts": [ [ "First appearance text line 1", "First appearance text line 2" ], [ "Second appearance text line 1", "Second appearance text line 2" ] ], ,
🌐
Unity
docs.unity3d.com › 2020.1 › Documentation › Manual › JSONSerialization.html
Unity - Manual: JSON Serialization
The JSON Serializer API supports any MonoBehaviour subclass, ScriptableObject subclass, or plain class or struct with the [Serializable] attribute. When you pass in an object to the standard Unity serializer for processing, the same rules and limitations apply as they do in the Inspector: Unity serializes fields only; and types like Dictionary<> are not supported.
🌐
Quora
quora.com › How-do-I-combine-two-list-items-and-form-JSON-data-in-Unity
How to combine two list items and form JSON data in Unity - Quora
Answer: How do I combine two list items and form JSON data in Unity? You’ll have to be more specific about combining two list items; do you mean you want to merge two lists together, or combine an item from each list? If you want to merge the lists then LINQ makes it easy: [code]var mergedLists...
🌐
Unity
discussions.unity.com › unity engine
Serialization of: List as JSON - Unity Engine - Unity Discussions
March 18, 2020 - I’m working on a little tool that lets me connect several GameObjects with a LineRenderer. It’s possible to connect multiple objects within one line. To store the Data of every connection, I’m saving the GameObject.name of every point in the connection in an array (string[ ]). Serializing this array as JSON worked without problems.
🌐
Unity
discussions.unity.com › unity engine
Saving a list of scriptable objects to JSON - Unity Engine - Unity Discussions
March 30, 2020 - I’m working on a quest system of sorts. I have a base class QuestAction which inherits from ScriptableObject, like this: public abstract class QuestAction: ScriptableObject From there I have many classes that derive from QuestAction class. For example, DialogueAction, TravelAction etc.They ...