I am trying to read a json file into my C# code. The json file contains the following string:
{
"allLevels": [{
"level": 1,
"name": "XXX",
"type": "XXX",
"description": "XXX",
"input": "XXX",
"key": "XXX",
"keyType": "XXX",
"output": "XXX"
},
{
"level": 2,
"name": "XXX",
"type": "XXX",
"description": "XXX",
"input": "XXX",
"key": "XXX",
"keyType": "XXX",
"output": "XXX"
}],
"funFacts": [
"XXX",
"XXXXX"
]
}
I have two classes, namely AllLevel.cs
and ContentJson.cs
which are shown as follows:
[System.Serializable]
public class AllLevel
{
public int level { get; set; }
public string name { get; set; }
public string type { get; set; }
public string description { get; set; }
public string input { get; set; }
public object key { get; set; }
public string keyType { get; set; }
public string output { get; set; }
}
using System.Collections.Generic;
[System.Serializable]
public class ContentJson
{
public IList<AllLevel> allLevels { get; set; }
public IList<string> funFacts { get; set; }
}
I am able to read the .json file, but not able to assign it to the ContentJson
object. The debug log in the code snippet below prints nothing but the string "ContentJson", and any attempt to access stuff inside the object gives NullReferenceException. Why is the FromJson not able to deserialize the object.
public static void populateGamedata(string gameDataFileName)
{
if (gameDataFileName == null)
return;
// Path.Combine combines strings into a file path
// Application.StreamingAssets points to Assets/StreamingAssets in the Editor, and the StreamingAssets folder in a build
string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a ContentJson object from it
ContentJson gameData = JsonUtility.FromJson<ContentJson>(dataAsJson);
// Retrieve the levels and funfacts property of gameData
levels = gameData.allLevels;
funFacts = gameData.funFacts;
Debug.Log("dataAsJson === " + dataAsJson);
Debug.Log("gameData == " + gameData.ToString());
Debug.Log("levels == " + levels[0].name);
}
else
{
Debug.LogError("Cannot load game data!");
}
}