Started trying to learn how Unity handles Json files today. After some reading I started trying to put together a small system to read in a Json file following
.
On run, I am getting the following error:
The TextAsset in my ItemCreator class below is properly filled as it is able to print the text to the log so I know I am overlooking something simple on JsonUtility.FromJson.
Base item class:
[System.Serializable]
public class Item
{
public int Number;
public string Type;
public double Speed;
}
Json item loader:
public class PitchLoader : MonoBehaviour
{
public Item myItem;
void Awake()
{
string loadedItem = ItemCreator.LoadJsonAsResource("pitchList.json");
myItem = JsonUtility.FromJson<Item>(loadedItem);
}
}
Item Creator:
public class ItemCreator
{
// Use this for initialization
public static string LoadJsonAsResource(string path)
{
string jsonFilePath = path.Replace(".json", "");
TextAsset loadedJsonFile = Resources.Load<TextAsset>(jsonFilePath);
Debug.Log(loadedJsonFile.text);
return loadedJsonFile.text;
}
}
This saved me!! I spent all day trying to figure out where I was going wrong with the script and the answer was a single comma in the JSON file. Thank You!
absolutely awful trying to do json in unity, even though I do it very often once in a while it takes me hours, so utterly annoying. just as I was about to paste my json and code, it somehow worked… i do wonder sometimes if its not compiling properly.
How is that relevant to this discussion of using malformatted json? Json has a strict and quite simple format as it is explained here. There can not be a trailing comma, neither in an object nor in an array. There may be json serializers which do not care, but strictly sticking to the format definition it’s invalid json.
Feel free to bookmark JsonLint.com. This page can validate your json and also beautifies it by applying some formatting rules.
Yes, Unity’s JsonUtility has some additional limitations. Specifically:
The top element has to be an object. No other json value is allowed / supported
Directly nested arrays are not supported. Having intermediate objects however does work
When it comes to object mapping, you actually need serializable classes to represent json objects and either arrays or Lists to represent arrays.
Specifically point 2 is just an artifact of how Unity’s own serialization system works and what constructs it supports.
If you have a problem of your own, please start a new thread.