JsonUtility返回一个空列表

时间:2019-03-04 19:01:21

标签: c# json unity3d

我正在尝试将某些项目存储为JSON文件,并在运行时获取它们。我正在尝试创建ItemDescription对象的列表。但是列表返回为空。我没有收到任何错误,但是当我放置一个断点时,我发现listOfItems之后是listOfItems = JsonUtility.FromJson<ItemList>(jsonString);为空。

 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.IO;

    public class ItemDictionary : MonoBehaviour
    {
        private Dictionary<ushort, ItemDescription> itemDictionary = new Dictionary<ushort, ItemDescription>();
        private ItemList listOfItems;

        private string path;

        void Start()
        {
            path = Application.streamingAssetsPath + "/itemDescription.json";
            if (File.Exists(path))
            {
                string jsonString = File.ReadAllText(path);
                listOfItems = JsonUtility.FromJson<ItemList>(jsonString);

                //Populate dictionary via JSON
                foreach (ItemDescription item in listOfItems.itemList)
                {
                    Debug.Log(item.itemName);
                    //itemDictionary.Add(item.id, item);
                }
            }
            else
            {
                Debug.LogError("ITEMDESCRIPTION FILE CANNOT BE FOUNDD");
            }

        }
    }


    [System.Serializable]
    public class ItemList
    {
        public List<ItemDescription> itemList;
    }

    [System.Serializable]
    public class ItemDescription
    {
        public string itemName;
        public ushort id;
        public string description;
        public ushort stack;
        public uint cost;
    }

JSON文件

{
  "Items": [
    {
      "itemName": "Regular Dirt",
      "id": 1,
      "description": "Dirty dirt",
      "stack": 500,
      "cost": 0
    },
    {
      "itemName": "Regular Stone",
      "id": 2,
      "description": "It's hard",
      "stack": 500,
      "cost": 0
    },
    {
      "itemName": "Regular Sand",
      "id": 4,
      "description": "It gets everywhere.",
      "stack": 500,
      "cost": 0 
    }
  ]
}

我已经尝试过将所有类型转换为字符串,将ItemDescription类重命名为Items,将ItemList类重命名为Items

1 个答案:

答案 0 :(得分:2)

尝试更改为此。

[System.Serializable]
public class ItemList
{
    public List<ItemDescription> Items;
}
相关问题