首页 > 解决方案 > 需要将从 JSON 文件解析的 List 对象分配给对象属性

问题描述

我试图构建 Magic The Gathering 卡片查看器并从 json 获取数据。我已经创建了 json 文件,然后将所有内容复制并粘贴到我的类中以生成模型。在使用 json 解析器的构造函数中,我很好地解析了对象,但是当我尝试分配给该对象属性时,我可以让方法检索所有卡片。但是当我试图这样做时,它说我不能隐式分配。我尝试分配 Cards = cardsCollection; 它抛出错误的地方。

命名空间 MTGArena
{
    公开课卡
    {

public class Rootobject { static Rootobject() { using (StreamReader file = new StreamReader("cards.json")) { string json = file.ReadToEnd(); Rootobject cardsCollection = JsonConvert.DeserializeObject<Rootobject>(json); Cards = cardsCollection; } } public static List<Card> Cards { get; set; } public static List<Card> GetCards() { return Cards; } } } public class Card { public string name { get; set; } public string set { get; set; } public Images images { get; set; } public string type { get; set; } public string[] cost { get; set; } public int cmc { get; set; } public string rarity { get; set; } public string cid { get; set; } public int?[] frame { get; set; } public string artist { get; set; } public string dfc { get; set; } public bool collectible { get; set; } public bool craftable { get; set; } public int dfcId { get; set; } public int rank { get; set; } public string grpId { get; set; } } public class Images { public string small { get; set; } public string normal { get; set; } public string large { get; set; } public string art_crop { get; set; } }

}

标签: c#

解决方案


换行:

Rootobject cardsCollection = JsonConvert.DeserializeObject<Rootobject>(json);

为了:

var cardsCollection = JsonConvert.DeserializeObject<List<Card>>(json);

推荐阅读