Ключ не найден, исключение - Unity Json - PullRequest
0 голосов
/ 17 мая 2018

Эй, ребята, у вас проблемы с реализацией следующей базы данных для Unity с Json из учебного пособия, которая искала часы, но не может найти проблему

Вот мой код: ItemDatabase.cs

public class ItemDatabase : MonoBehaviour {
    private List<Item> database = new List<Item>(); // Json database
    private JsonData itemData;

    void Start()
    {
        itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.Json")); // change from json object to be readible by c#
        ConstructItemDatabase();

        Debug.Log(database[1].Value);
    }

    void ConstructItemDatabase()
    {
        for (int i = 0; i < itemData.Count; i++)
        {
            database.Add(new Item(
                (int)itemData[i]["id"],
                itemData[i]["title"].ToString(),
                (int)itemData[i]["stats"]["value"],
                (int)itemData[i]["stats"]["power"],
                (int)itemData[i]["stats"]["defence"],
                (int)itemData[i]["stats"]["vitality"],
                itemData[i]["description"].ToString(),
                (bool)itemData[i]["stackable"],
                (int)itemData[i]["rarity"],
                itemData[i]["slug"].ToString()));
        }
    }

}

public class Item
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public int Value { get; set; }
        public int Defence { get; set; }
        public int Power { get; set; }
        public int Vitality { get; set; }
        public string Description { get; set; }
        public bool Stackable { get; set; }
        public int Rarity { get; set; }
        public string Slug { get; set; }

    public Item(int id, string title, int value, int power , int defence, int vitality, string description, bool stackable, int rarity, string slug)
        {
            this.ID = id;
            this.Title = title;
            this.Value = value;
            this.Defence = defence;
            this.Power = power;
            this.Vitality = vitality;
            this.Description = description;
            this.Stackable = stackable;
            this.Rarity = rarity;
            this.Slug = slug;

        }

    public Item()
        {
            this.ID = -1;
        }
    }

и мой код для файла json Items.json

[
    {
        "id": 0,
        "title": "Steel Gloves",
        "value": 6,
        "stats": {
            "power": 1,
            "defence": 4,
            "vitality": 2
        },
        "description": "Gloves with steel plating",
        "stackable": false,
        "rarity": 2,
        "slug": "steel_gloves"
    },
    {
        "id": 1,
        "title": "The Great Stick",
        "value": 543,
        "stats": {
            "power": 56,
            "defence": 2,
            "vitality": 54
        },
        "description": "A Stick that's pretty great",
        "stackable": true,
        "rarity": 6,
        "slug": "the_great_stick"
    }
]

Когда я отлаживаю программу из visual studio, она работает просто отлично, однако в Unity при нажатии на кнопку play я получаю некоторые ошибки:

KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.String,LitJson.JsonData].get_Item (System.String key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
LitJson.JsonData.get_Item (System.String prop_name)
ItemDatabase.ConstructItemDatabase () (at Assets/Scripts/ItemDatabase.cs:27)
ItemDatabase.Start () (at Assets/Scripts/ItemDatabase.cs:15)

Я думал, что неправильно записал одну из строк в ContructItemDatabase (), но мне кажется, что я проверил это 100 раз.

Любая помощь приветствуется, спасибо

1 Ответ

0 голосов
/ 17 мая 2018

Ваш класс должен выглядеть следующим образом

public class Stats
{
    public int power { get; set; }
    public int defence { get; set; }
    public int vitality { get; set; }
}

public class items
{
    public int id { get; set; }
    public string title { get; set; }
    public int value { get; set; }
    public Stats stats { get; set; }
    public string description { get; set; }
    public bool stackable { get; set; }
    public int rarity { get; set; }
    public string slug { get; set; }
}

, потому что "сила", "защита", "жизненная сила" находятся под "характеристиками".

Во-вторых, я рекомендую вам использовать Newtonsoft , чтобы получить JSON такого типа в объектах.Что я считаю очень легко понять.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...