Unity: десериализовать строку json в объект C#
Я пытаюсь прочитать файл JSON в мой код C#. Файл json содержит следующую строку:
{
"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"
]
}
У меня есть два класса, а именно AllLevel.cs
а также ContentJson.cs
которые показаны следующим образом:
[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; }
}
Я могу прочитать файл.json, но не могу назначить его ContentJson
объект. В журнале отладки в приведенном ниже фрагменте кода ничего не печатается, кроме строки "ContentJson", а любая попытка получить доступ к содержимому внутри объекта дает исключение NullReferenceException. Почему FromJson не может десериализовать объект.
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!");
}
}