【问题标题】:JsonUtility returning an empty listJsonUtility 返回一个空列表
【发布时间】:2019-03-04 19:01:20
【问题描述】:

我试图将一些项目存储为 JSON 文件并在运行时获取它们。我正在尝试创建 ItemDescription 对象的列表。但列表返回空。我没有收到任何错误,但是当我设置断点时,我看到listOfItemslistOfItems = 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

【问题讨论】:

标签: c# json unity3d


【解决方案1】:

试着改成这个。

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

【讨论】:

  • 哇!那解决了它!是因为我在 JSON 文件中定义了“项目”吗?非常感谢!
  • @D.Haritheesan 不,这是因为您将其声明为 private "具有不受支持类型的字段以及 private 字段或标有 NonSerialized 属性的字段将被忽略。” - 直接来自我在 cmets 中链接到的文档。
  • 是的,命名确实很重要。我总是通过这个运行我的 json 来给我一个起始模板并从那里开始。 json2csharp.com
  • @RyanWilson 嘿,抱歉,没有看到链接。我还公开了子类中的所有字段。你在说private ItemList listOfItems;吗?
  • @RyanWilson 不,实际上是因为 OP 的字段名称 itemList 与 JSON 中给出的 Itmes 不匹配;)
猜你喜欢
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多