使用Unity JsonUtility反序列化JSON数组无法获取序列化值

4
我正在尝试将JSON中的卡片信息反序列化以在Unity游戏中使用,但效果不太好。我已经测试了要反序列化的类,并且可以手动创建这些类的对象,但反序列化器不能正确地创建它们。
当我运行反序列化逻辑时,结果数组的大小是正确的,但是卡片的代价(Cost)和名称(Name)字段都没有填入,最终得到了一组未初始化的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对象文件,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”是完全不变的吗?还是这个类里面有更多的内容?比如基类。 - Cid
以上就是Cards文件的确切内容,没有多余的也没有缺失的。 - Lucas Burns
1个回答

2

没错,问题已经解决了。我完全没有想到添加getter/setter部分会从根本上改变变量,谢谢! - Lucas Burns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接