- Home /
Saving a list to json
Hey all, I'm having trouble saving out to a json file. I built up a small mock program to show what I'm attempting to do.
public class Contoller : MonoBehaviour
{
private string installPath;
private bool directoryExists;
private string jsonString;
private Store lots_o_stuff = new Store ();
private Product food = new Product ();
private Product cloths = new Product ();
void Start ()
{
installPath = Path.GetDirectoryName (Application.dataPath);
checkForDirectory ();
checkForStore ();
Debug.Log (lots_o_stuff.product [0].item_Name [0]);
}
private void checkForDirectory ()
{
try {
if (!Directory.Exists (installPath + "/Configs")) {
Directory.CreateDirectory (installPath + "/Configs");
directoryExists = true;
} else {
directoryExists = true;
}
} catch {
Debug.Log ("Failed Directory");
}
}
private void checkForStore ()
{
if (directoryExists) {
try {
if (!File.Exists (installPath + "/Configs/Store.json")) {
buildDefaultStore ();
jsonString = JsonUtility.ToJson (lots_o_stuff, true);
File.WriteAllText (installPath + "/Configs/Store.json", jsonString);
}
} catch {
Debug.Log ("Failed Store");
}
}
}
private void buildDefaultStore ()
{
lots_o_stuff.store_Name = "Lots O Stuff";
lots_o_stuff.store_Address = "123 Adress St.";
string[] food_Items = new string[] { "Banana", "Apple", "Shrimp", "Ice Cream" };
string[] cloth_Items = new string[] { "Shirt", "Pants", "Belt", "Boots" };
food.Type = "Food";
food.item_Name.AddRange (food_Items);
cloths.Type = "Cloths";
cloths.item_Name.AddRange (cloth_Items);
lots_o_stuff.product.Add (food);
lots_o_stuff.product.Add (cloths);
}
}
public class Store
{
public string store_Name;
public string store_Address;
public List<Product> product = new List<Product> ();
}
public class Product
{
public string Type;
public List<string> item_Name = new List<string> ();
}
When I go to save out, this is all that gets saved.
{
"store_Name": "Lots O Stuff",
"store_Address": "123 Adress St."
}
The list "Product" doesn't even show up empty.
Does anyone know a way to make this work?
Comment
Best Answer
Answer by Bunny83 · Nov 23, 2019 at 11:53 AM
You haven't marked any of your classes as [System.Serializable]
Your answer
![](https://koobas.hobune.stream/wayback/20220612215207im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
JSON file not written/read on application exit on android 1 Answer
Instancing ScriptableObject at Runtime, loading and saving via JsonUtility 1 Answer
Storing list aka "save function" 3 Answers
How to save and load mobs? 0 Answers
Serializing lists 0 Answers