- Home /
Load json into array class
I'm trying to load data from a json file into an array class but have hit the wall in how it should be done, so hope that someone here can give me a hint on what I have been doing wrong with the code on how to load the data into the array - this line is in error: PlayerDialogues = JsonUtility.FromJson(jsonFile.text);
public class Initializer : MonoBehaviour { public TextAsset jsonFile; public Dialogues[] PlayerDialogues;
private void Awake()
{
PlayerDialogues = new Dialogues[30];
PlayerDialogues = JsonUtility.FromJson<Dialogues>(jsonFile.text);
}
[System.Serializable]
public class Dialogues
{
public int Weight;
public int Level;
[TextArea]
public string Text;
}
}
To do that, I recommend the following workaround:
Create a Serializable class that wraps your array
[System.Serializable] public class DialoguesArray { public Dialogues[] playerDialogues; }
[System.Serializable] public class Dialogues { public int Weight; public int Level; [TextArea] public string Text; }
Be sure that your JSON is in this format:
{ "playerDialogues":[ { "weight":#, "level":#, "text":# }, { "weight":#, "level":#, "text":# } ] }
Use the JSON Utility class
DialoguesArray PlayerDialogues = JsonUtility.FromJson(jsonFile.text);
Acces your data
int weight = PlayerDialogues.playerDialogues[0].weight;
This has worked for me with the JsonUtility class, but I think other libraries manage the JSON serialization in a more friendly way.
Hope it helps.
Answer by PinkBishop · Jan 06, 2021 at 09:45 AM
After some digging around I found a solution by using this script below and did a "quick" fix to the existing json because it is exported from a winforms app that uses Newtonsoft that does (apparently) not export with the "{ "playerDialogues":" infront of the json file. So when I need to load the json file I do this fix:
public TextAsset jsonFile; public Dialogues[] PlayerDialogues;
private void Awake()
{
string str = "{\"Character\":" + jsonFile.text + "}";
PlayerDialogues = JsonHelper.FromJson<Dialogues>(str);
}
public static class JsonHelper { public static T[] FromJson(string json) { Wrapper wrapper = JsonUtility.FromJson (json); return wrapper.Character; }
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Character = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Character = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[System.Serializable]
private class Wrapper<T>
{
public T[] Character;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to read an int array using LitJson? 1 Answer
Distribute terrain in zones 3 Answers