我有一个Json文件,格式如下:
slave-read-only no
我正在使用以下代码将其放入列表中:
"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"]}
Visual Studio告诉我,Json的“可爱的小猫”部分无法反序列化。通常我会删除代码的那一部分,但它是一个近40000行长的文件的摘录,所以删除每个项目的那个将是不切实际的。另外,当我在排除故障时删除“可爱的小猫”时,我的“布局”也出现了类似的错误。错误说我需要将它放入Json数组或更改反序列化的类型,以便它是正常的.Net类型。谁能指出我做错了什么?
答案 0 :(得分:2)
如果您的示例确实是您正在做的事情,那么您只需将其反序列化为错误的类型。
现在您的代码适用于以下内容:
[{"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文件的示例不是有效的JSON(除非您遗漏了整个事物的花括号),因此您需要修复该文件。如果你真的希望在JSON中有一个Items列表,那么将所有内容包装在一个数组中将是表示它的正确方法。
答案 1 :(得分:0)
首先检查您收到的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。