【问题标题】:Deserializing JSON array with Unity JsonUtility fails to get serialized values使用 Unity JsonUtility 反序列化 JSON 数组无法获取序列化值
【发布时间】:2019-10-12 02:01:28
【问题描述】:

我正在尝试从 JSON 中反序列化卡片信息以在 Unity 游戏中使用,但它运行不正确。我已经测试了我试图反序列化的类,我可以为它们手动创建对象,但是反序列化器无法正确创建它们。

当我运行反序列化逻辑时,结果数组的大小是正确的,但是卡片的 CostName 字段都没有填写,我只剩下一组未初始化的 Card 对象。

我的相关代码如下:

我们反序列化的文件,Game.cs:

using System.IO;
using UnityEngine;
public class Game {

    private CardsCollection allCards;    

    private void LoadJson()
    {
        ...
        // Find the path to our JSON file
        // Save the path as "path"

        // I have verified this line gets the correct json data as a string
        string json = File.ReadAllText(path); 

        // Convert the json string into a deserialized array of objects
        // using the CardsCollection wrapper
        allCards = JsonUtility.FromJson<CardsCollection>(json);
    }

}

卡片对象文件,Card.cs:

using System;
[Serializable]
public class Card
{
    public string Name { get; set; }
    public int Cost    { get; set; }

    public Card(string Name, int Cost)
    {
        this.Name = Name;
        this.Cost = Cost;
    }
}

[Serializable]
public class CardsCollection
{
    public Card[] cards;
}

最后是 JSON 本身:

{
    "cards": [
        {
            "Name": "copper",
            "Cost": 0
        },
        {
            "Name": "silver",
            "Cost": 3
        },
        {
            "Name": "gold",
            "Cost": 6
        },
        {
            "Name": "curse",
            "Cost": 0
        },
        {
            "Name": "estate",
            "Cost": 2
        },
        {
            "Name": "duchy",
            "Cost": 5
        },
        {
            "Name": "province",
            "Cost": 8
        }
    ]
}

【问题讨论】:

  • Cards 是否完全一样?还是那堂课有更多的内容?比如基类
  • 以上是Cards文件的确切内容,没有多余的,没有遗漏

标签: c# json unity3d


【解决方案1】:

Json 序列化只能处理字段(请参阅支持的类型 https://docs.unity3d.com/Manual/JSONSerialization.html)但您的 Name 和 Cost 看起来像属性 What is the difference between a field and a property?

由于它们被标记为公开并且无论如何都可以直接访问,因此我只需删除 {get;设置}

【讨论】:

  • 是的,已经解决了。我不知道添加 getter/setter 部分会从根本上改变变量,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 2018-12-18
相关资源
最近更新 更多