我在我的代碼有很多麻煩,我試圖做某種解析器。基本上我試圖從JSON文件中獲取數據,並使用該數據從我的代碼中調用方法。C#/ JSON - 調用一個列表<object>作爲參數的方法
這是我的JSON文件
{ "story": { "Talk": [ "me", 1, 1 ] } }
的一個基本的例子現在我有一類叫做DialogueSystem
,它含有一種叫Talk
有三個參數,字符串,INT,INT功能。
我正在使用SimpleJSON
來獲取我的JSON數據,但我猜測它與其他JSON解析器相似。
另外,我有這有不同的參數,這就是爲什麼我不得不使用反射
不管怎麼說,這裏是一個獲取JSON數據的代碼,並嘗試使用反射來調用通話方法等功能。
// Gets the JSON and parses it
JSONNode Node = JSONNode.Parse(jsonFile());
var method = sys.GetType().GetMethod(""); // Reflection stuff
foreach (JSONNode item in Node["story"].Keys) // the Keys just gives me every key that's in the story node/key
{
List<object> parameters = new List<object>(); // List containing the parameters, to be used when invoking the method
for (int i = 0; i < Node["story"][item].Count; i++)
{
//This part tests if it's a string or int and adds it as such
string data = Node["story"][item][i];
int n;
bool isNum = int.TryParse(data, out n);
if (isNum)
{
parameters.Add(n);
}
else
{
parameters.Add(data);
}
}
// Invoke the method using it's method name and the method parameters
method.Invoke(item, parameters.ToArray());
}
btw,我的Talk
類只是基於給定的輸入打印文本。
出於某種原因,我得到這個錯誤
的NullReferenceException:未設置爲一個 對象Dialogue.StoryTeller.ReadStory(Dialogue.DialogueSystem SYS)的實例對象引用 (在資產/對話系統/ Scripts/StoryTeller.cs:57)
如果你有任何想法如何解決它,或者可能做得更好,那太棒了!
謝謝!
我只能在2天內將它標記爲答案,所以我現在要說它 – PandawanFr