[英]Serializing a JSON file returns null object when acccessing child objects
我正在嘗試讀取包含各種對象的本地 JSON 文件。 但是對象總是返回null。
我知道Resources.Load<TextAsset>(_directory + _fileName).text;
已成功找到該文件,因為我可以將文本輸出到控制台。
我的目標是能夠請求密鑰並取回所選語言的值。 即: hello_world.sp
將返回Hola, mundo
。
但是,無論何時我去訪問任何對象,如Debug.Log(lang.languageList.Count);
我收到錯誤:
NullReferenceException:未將對象引用設置為對象的實例
最終,我希望能夠添加額外的語言值, fr
, it
等......
誰能看到我做錯了什么?
語言文件
{
"hello_world": {
"en": "Hello, World!",
"sp": "Hola, mundo"
},
"button_ok": {
"en": "Yes",
"sp": "Si"
},
"button_cancel": {
"en": "Cancel",
"sp": "Cancelar"
}
}
JSONLoad.cs
public class JSONLoader
{
private static readonly string _directory = "Langs/";
private static readonly string _fileName = "lang";
private string ReadJsonFile() { return Resources.Load<TextAsset>(_directory + _fileName).text; }
public void Load()
{
var file = ReadJsonFile();
var lang = JsonUtility.FromJson<LanguageObject>(file);
Debug.Log(lang);
}
}
[Serializable]
public class LangValue
{
public string en { get; set; }
public string sp { get; set; }
}
[Serializable]
public class LangKey
{
public string id { get; set; }
public List<LangValue> children { get; set; }
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList { set; get; }
}
根據文檔,使用UnityEngine.JsonUtility
JSON 序列化依賴於具有公共字段而不是屬性的模型。 您需要使用字段而不是屬性來定義模型。
IE。,
[Serializable]
public class LangValue
{
public string en;
public string sp;
}
[Serializable]
public class LangKey
{
public string id;
public List<LangValue> children;
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList;
}
您的 Json 結構與您的課程不匹配。 這不是一個列表。 這是一個工作示例:
傑森:
{
"languageList":
[
{
"id": "hello_world",
"children": {
"en": "Hello, World!",
"sp": "Hola, mundo"
}
},
{
"id": "button_ok",
"children": {
"en": "Yes",
"sp": "Si"
}
},
{
"id": "button_cancel",
"children": {
"en": "Cancel",
"sp": "Cancelar"
}
}
]
}
課程:
[Serializable]
public class LangValue
{
public string en;
public string sp;
}
[Serializable]
public class LangKey
{
public string id;
public LangValue children;
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList;
}
PS:我不是JsonUtility
的粉絲,我寧願選擇Json.Net
,它允許使用屬性等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.