c# - 使用Unity JsonUtility反序列化JSON数组获取序列化值失败

标签 c# json unity3d

我正在尝试从 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 对象文件,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
        }
    ]
}

最佳答案

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

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

关于c# - 使用Unity JsonUtility反序列化JSON数组获取序列化值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310055/

相关文章:

c# - 用C#模拟批处理文件

c# - 我应该直接在代码隐藏中使用 Linq To SQL 还是使用其他方法?

javascript - "Unexpected end of input"消息从简单的 POST 请求到 node.js 的响应

c# - WCF - 如何使用 JavascriptSerializer 作为我的反序列化器?

plugins - 可以更改 OpenGL 纹理名称吗?

c# - Unity 中的 MIDI 输出

c# - 获取 Unity 中游戏对象的所有组件的列表

c# - 在 c# 中使用 unity 在简历上重新启动应用程序

c# - 在 visual studio 2015 中发布 xamarin 应用程序

json - 在 R 中从 JSON 转换为数据帧