C# 修复此 Json 反序列化类型错误?

C# fix this Json deserialization type error?

我有一个 Json 文件,格式如下:

  "Adorable Kitten": {"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}

我正在使用以下代码将其放入列表中:

using (StreamReader r = new StreamReader(filepath))
                {
                    string json = r.ReadToEnd();
                    List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
                    textBox1.Text = items[0].name.ToString();
                }
public class Item
        {
            public string layout;
            public string name;
            public string manaCost;
            public string cmc;
            public string[] colors;
            public string type;
            public string[] types;
            public string[] subtypes;
            public string text;
            public string power;
            public string toughness;
            public string imageName;
            public string[] colorIdentity;
        }

Visual Studio 告诉我 Json 的 "Adorable Kitten" 部分无法反序列化。通常我会删除那部分代码,但它是从一个将近 40000 行长的文件中摘录的,因此为每个项目删除它是不切实际的。此外,当我在排除故障时删除 "Adorable Kitten" 时,我得到了 "layout" 的类似错误。该错误表明我需要将其放入 Json 数组或更改反序列化类型,使其成为普通的 .Net 类型。谁能指出我做错了什么?

如果您的示例确实是您正在做的,那么您只是反序列化为错误的类型。

现在您的代码适用于以下情况:

[{"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}]

请注意,它是 JSON 数组中的单个 JSON 对象。这对应于您要反序列化的类型 (List<Item>).

您发布的 JSON 文件示例无效 [​​=20=](除非您遗漏的整个内容周围有大括号),因此您需要修复该文件。如果您真的希望 JSON 中有一个项目列表,那么将所有内容包装在一个数组中将是表示它的正确方法。

首先检查一下你收到的JSON是否有效JSON,显然你收到的是错误的,你可以检查一下https://jsonlint.com

第二次为JSON创建模型,你可以在这里做http://json2csharp.com

public class AdorableKitten
{
    public string layout { get; set; }
    public string name { get; set; }
    public string manaCost { get; set; }
    public int cmc { get; set; }
    public List<string> colors { get; set; }
    public string type { get; set; }
    public List<string> types { get; set; }
    public List<string> subtypes { get; set; }
    public string text { get; set; }
    public string power { get; set; }
    public string toughness { get; set; }
    public string imageName { get; set; }
    public List<string> colorIdentity { get; set;
    }
}

不要忘记模型上的 getter 和 setter。