我在我的代码有很多麻烦,我试图做某种解析器。基本上我试图从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