I am trying to mod a Unity game using BepInEx. I want to read a list of a type of class I've created from a JSON, then read each object from that class. I used UnityEngine.JsonUtility to do this and created a wrapper class containing my list.
[System.Serializable]
public class StarSignDataList
{
public List<StarSignData> starSigns;
}
// Stores all data pertaining to star signs as read from JSON file.
[System.Serializable]
public class StarSignData
{
public string name;
public int id;
public string description;
}
Then I read the json file from the correct file path, parsing that information into a string and called the JsonUtility.FromJason() method to convert the string into my StarSignDataList class.
// Reads all star sign data from JSON and assigns values to list.
public static void InitializeData()
{
log.LogInfo("Initializing Star Sign data.");
string json = File.ReadAllText("BepInEx/plugins/StarSigns/starsigns.json");
log.LogInfo(json);
StarSignDataList list = UnityEngine.JsonUtility.FromJson<StarSignDataList>(json);
log.LogWarning(list.starSigns.Count == 0 ? "Not null" : "Null!");
log.LogInfo(list.starSigns[0].name);
signs = list.starSigns;
foreach (StarSignData data in signs)
{
log.LogInfo(data.name);
}
}
When I print out the contents of my json immediately after reading it, it comes out as expected, looking exactly like my json file. However when I convert the json string into my list class, the list is completely empty and then throws a NullReferenceException when trying to print the first object. I've trying using arrays instead of lists, I've checked that my json is correctly written, I've pored over countless google search results without success.
Here is my json file.
{
"starSigns": [
{
"name": "Sign of the Fool",
"id": 0,
"description": "You are of normal birth."
},
{
"name": "Sign of Loki",
"id": 1,
"description": "The sign of the god of betrayal shone above your birth place."
},
{
"name": "Sign of Odin",
"id": 2,
"description": "A tumultuous child at birth, your muscles bear the strength of Odin himself."
}
]
}
Out of desperation I tried converting a class like this to a json, and it just wrote to the file "{ }". When I try to do the same with just my StarSignData class it works as expected, but I need to put multiple objects in my json and the list class does not seem to work. I also can't use external libraries such as SimpleJson for this.