我一直在使用Unity引擎來構建英語語言遊戲。我正在努力讓C#解析JSON。C#,Unity3D,JSON解析:無法解析JSON到C#對象
我一直在試圖讓JSON解析過去幾天失敗。我已經驗證了JSON,可以將jsonString調試到控制檯,但只要jsonUtility在json上得到它的手,那麼我最終會得到一個NULL數據的負載。
這裏是我的JSON:
{"question": {"questionType": "0", "categoryID": "0", "bonusBool": "FALSE", "answerText": "cake", "questionText": "If something is really easy to do, it\u2019s a piece of \u2026\u2026\u2026 \\n a. pie \\n b. tart \\n c. cake", "ID": "0"}}
這裏是我的C#:
[System.Serializable]
public class QuestionDataAsString
{
public string questionText;
public string answerText;
public string categoryID;
public string ID;
public string questionType;
public string bonusBool;
}
[System.Serializable]
public class Question{
public string questionText;
public string answerText;
public int categoryID;
public int ID;
public int questionType;
public bool bonusBool;
}
public static void LoadQuestion()
{
string filePath = Path.Combine(Application.streamingAssetsPath, "questionData.json");
string dataAsJSON = File.ReadAllText(filePath);
Debug.Log(dataAsJSON);
QuestionDataAsString question = JsonUtility.FromJson<QuestionDataAsString>(dataAsJSON);
Debug.Log(question.questionText);
}
public static Question ConvertQuestionDataFromString(QuestionDataAsString stringData)
{
Question question = new Question();
question.questionText = stringData.questionText;
question.answerText = stringData.answerText;
question.categoryID = int.Parse(stringData.categoryID);
question.ID = int.Parse(stringData.ID);
question.questionType = int.Parse(stringData.questionType);
question.bonusBool = Boolean.Parse(stringData.bonusBool);
return question;
}
當我經歷了閃屏控制器運行LoadQuestion,我可登錄JSON到控制檯的字符串。但是,一旦我使用jsonUtility,我會得到Null對象。
這是控制檯輸出:
{"question": {"questionType": "0", "categoryID": "0", "bonusBool": "FALSE", "answerText": "cake", "questionText": "If something is really easy to do, it\u2019s a piece of \u2026\u2026\u2026 \\n a. pie \\n b. tart \\n c. cake", "ID": "0"}}
UnityEngine.Debug:Log(Object)
SaveLoadManager:LoadQuestion() (at Assets/Scripts/SaveLoadManager.cs:91)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/SplashController.cs:18)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
Null
UnityEngine.Debug:Log(Object)
SaveLoadManager:LoadQuestion() (at Assets/Scripts/SaveLoadManager.cs:93)
<Start>c__Iterator0:MoveNext() (at Assets/Scripts/SplashController.cs:18)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
我經過這裏的答案,團結回答搜查,但沒有發現任何相關的解決方案。
任何想法爲什麼從json迴歸零?
您的JSON不符合您的C#類結構。 – DavidG
祝你好運使用該JSON類,因爲該統一不會Deseralize JSON低於7嵌套級別 –
@ johnny5有什麼問題?這隻有2個級別。 – DavidG