[SOLVED] Converting a Generic List to JSON in Unity
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.
I followed the tutorial, that works fine with others classes, but when I did this:
 string dataAsJson = JsonUtility.ToJson(tilesMap);
 string filePath = Application.dataPath + "/Maps/" + generatedLevelFileName + ".json";
 File.WriteAllText(filePath, dataAsJson);
 
               I simply, get this:
Example File: "Application.dataPath/Maps/level1.json" Content:
 {}
 
               Thanks in advance!
Answer by c8theino · Dec 10, 2021 at 07:43 AM
I found a great way to serialize generic lists. This works at least on Unity version 2020.3.
 using System.Collections.Generic;
 using UnityEngine;
 
 [System.Serializable]
 public class SerializableList<T> {
     public List<T> list;
 }
 
 public class ListToJsonExample : MonoBehaviour {
     [SerializeField] private SerializableList<string> names;
 
     private void Awake() {
         names.list.Add("Mark");
         names.list.Add("Luke");
 
         string json = JsonUtility.ToJson(names);
 
         Debug.Log(json);
     }
 }
 
               Prints:
 {"list":["Mark","Luke"]}
 
              This works! Thank you! I also add an extension function for the List. Hope this helps.
 public static class ListExtention {
     public static SerializableList<T> ToSerializable<T>(this List<T> list)
     {
         return new SerializableList<T>() {list = list};
     }
 }
                 Answer by Catonyourhead · Jul 26, 2018 at 03:58 AM
I am having the same problem. My code is a bit longer, but I am trying to save the names of my gameobjects in a Json formatted list... I'm having no luck figuring out what my problem is on the forums. When I go to convert the list, Json just returns "{ }". Here is my code:
[Serializable] public class SaveLoad : Inventory {
 private static GameObject player;
 private static System.Collections.Generic.List<string> Wpns = new System.Collections.Generic.List<string>();
 private static System.Collections.Generic.List<string> Cnsm = new System.Collections.Generic.List<string>();
 private static System.Collections.Generic.List<string> Keys = new System.Collections.Generic.List<string>();
 private static System.Collections.Generic.List<string> Placeholder = new System.Collections.Generic.List<string>();
 private static System.Collections.Generic.List<int> PlySas = new System.Collections.Generic.List<int>();
 private static System.Collections.Generic.List<int> IsoSas = new System.Collections.Generic.List<int>();
 private static string nameHolder;
 
 private static string json;
 private static string SAVE_FILE;
 
 protected  static void Save() {
 SAVE_FILE = Stats.PlayerName + ".json";
     /////Convert each to list/////
     if (Wpns != null)
     {
         Wpns.Clear();
     }
     Wpns = ToList(Inventory.Weapons);
     SaveJSON("Weapons", Wpns);
     if (Keys != null)
     {
         Keys.Clear();
     }
     Keys = ToList(Inventory.KeyItems);
     SaveJSON("KeyItems", Keys);
     if (Cnsm != null)   
     {
         Cnsm.Clear();
     }
     Cnsm = ToList(Inventory.Consumables);
     SaveJSON("Consumables", Cnsm);
     ////Save in as JSON////
 }
 private static System.Collections.Generic.List<string> ToList(GameObject[] array)
 {
     if (Placeholder != null)
     {
         Placeholder.Clear();
     }
     Placeholder = new System.Collections.Generic.List<string>();
     for (int i = 0; i <= (array.Length - 1); i++)
     {
         if (array[i])
         {
             nameHolder = array[i].name;
             Placeholder.Add(nameHolder);
         }
     }
     return Placeholder;
 }
 private static void SaveJSON(string type, System.Collections.Generic.List<string> list )
 {
     json = JsonUtility.ToJson(list);
     print(json + " " + type);
     string filename = Path.Combine(Application.persistentDataPath, type + SAVE_FILE);
     if (File.Exists(filename)) {
         File.Delete(filename);
     }
     File.WriteAllText(filename, json);
 }
 
               }
I solved my problem by Serializing my classes.
 [Serializable]
 public class $$anonymous$$yClass
 {
     public int level;
     public float timeElapsed;
     public string playerName;
 }
 
                  For more info look at this: JSON Serialization
Answer by kskjadav007 · Jun 29, 2021 at 06:28 AM
i wanted to convert the list to JSON so i did something like this
 [System.Serializable]
 public class _Recentplayers
 {
     public List<_UserDetails> m_recent_players;
 }
 
 [System.Serializable]
 public class _UserDetails
 {
     public string m_username;
     public string m_my_name;
 }
 
               And then
             m_users = new _Recentplayers();
             m_ud = new _UserDetails();
 
             m_ud.m_my_name = "";
             m_ud.m_user_name = "";
 
             m_users.m_recent_players.Add(m_ud);
             string json = JsonUtility.ToJson(m_users);
 
             Debug.Log(json);
 
              Your answer
 
             Follow this Question
Related Questions
Error when adding an item to a list 0 Answers
how do you Deserialize JSON in a list? 0 Answers
Maximum number of hexagons in one map? 1 Answer
Help with dynamic loading or occlusion culling in scenes on 2D metroidvania? 1 Answer
Create a list of BaseType where different supertypes are contained. 0 Answers