我正在尝试从JSON中反序列化卡信息以用于Unity游戏,但这种方法运行不正常。我已经测试了要反序列化的类,可以为它们手动创建对象,但是反序列化器无法正确创建它们。
运行反序列化逻辑时,结果数组的大小正确,但卡的Cost
或Name
字段均未填写,并且剩下未初始化的数组{ {1}}个对象。
我拥有的相关代码如下:
我们反序列化的文件Game.cs:
Card
Card对象文件Card.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);
}
}
最后是JSON本身:
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;
}
答案 0 :(得分:1)
Json序列化只能处理字段(请参阅受支持的类型https://docs.unity3d.com/Manual/JSONSerialization.html),但是您的Name和Cost看起来像属性What is the difference between a field and a property?
由于它们被标记为公开,而且无论如何都可以直接访问,所以我将删除{get;设置}