【问题标题】:Load multiple 'nodes' from JSON and store into array从 JSON 加载多个“节点”并存储到数组中
【发布时间】:2016-02-29 12:40:36
【问题描述】:

我目前正在创建一个基于文本的小型游戏。在这显然有多个房间,我希望从 JSON 文件加载这些房间。我目前正在这样做:

        dynamic jRooms = Json.Decode(file);
        for (int i = 0; i < Regex.Matches( file,  "Room" ).Count; i++){
            name[i] = jRooms.Game.Room[i];
            description[i] = jRooms.Game.Room.Attributes.Description[i];
            exits[i] = jRooms.Game.Room.Attributes.Exits[i];
            _count++;
        }

从以下 JSON 文件加载信息:

{
'Game': [{
    'Room': 'Vault 111 Freeze Chamber',
        'Attributes': { 
            'Description': 'The freeze chamber of the vault you entered after the nuclear fallout.',
            'Exits': 'North.Vault 111: Main Hallway'
        },
    'Room': 'Vault 111 Main Hallway',
        'Attributes': { 
            'Description': 'The main hallway of the vault.',
            'Exits': 'South.Vault 111: Freeze Chamber'
        }
    }]}

不幸的是,这在运行时引发了一个我似乎无法解决的错误,如下所示:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法对空引用执行运行时绑定 在 CallSite.Target(闭包,CallSite,对象,Int32) 在 System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,Tret](CallSite 站点,T0 arg0,T1 arg1) 在 TBA.Loader.Rooms() 在 TBA.Program.Main(String[] args)

任何帮助都将不胜感激,因为我完全不知道什么是错误的并且不起作用。如果您需要我的代码,请索取。

谢谢。

【问题讨论】:

    标签: c# json


    【解决方案1】:

    问题在于您的 JSON。 JSON 不允许单引号(也许它们有不同的含义或根本没有含义)。来源-W3Schools.

    使用 JSONLint 等服务来验证 JSON 并检查错误。甚至 JSONLint 也声明您的 JSON 无效。然而,使用双引号,它被声明为有效。你应该像这样使用双引号:

    {
        "Game": [
            {
                "Room": "Vault111FreezeChamber",
                "Attributes": {
                    "Description": "Thefreezechamberofthevaultyouenteredafterthenuclearfallout.",
                    "Exits": "North.Vault111: MainHallway"
                },
                "Room": "Vault111MainHallway",
                "Attributes": {
                    "Description": "Themainhallwayofthevault.",
                    "Exits": "South.Vault111: FreezeChamber"
                }
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2021-10-28
      • 2019-01-11
      • 2012-01-08
      相关资源
      最近更新 更多