【发布时间】:2022-08-15 03:24:28
【问题描述】:
我是一个新手,我第一次尝试将数据从 json 文件导入 c# 应用程序。在这种情况下,我正在制作一个应用程序来组织和管理我正在玩的制作视频游戏的食谱。
我有一个包含我的食谱信息的 json 文件;
{
\"assembler_recipes\":[
{
\"ItemProduced\":\"AI_Limiter\",
\"ProductionCount\":5,
\"Resources\":{
\"iron_Plate\":11.25,
\"rubber\":3.75
},
\"Byproducts\":{
}
},
{
\"ItemProduced\":\"alclad_Aluminium_Sheet\",
\"ProductionCount\":30,
\"Resources\":{
\"aluminium_Ingot\":30,
\"copper_Ingot\":10
},
\"Byproducts\":{
}
}, // etc...
]
}
以及我希望它采用的格式;
public class Recipe
{
public KeyValuePair<Items, decimal> Produces { get; set; }
public Dictionary<Items,decimal> Resources { get; set; }
public Dictionary<Items, decimal> Byproducts { get; set; }
}
这是我的导入方法;
public class Recipe_List
{
public Recipe_List()
{
var dataFile = File.ReadAllText(\"C:\\\\Users\\\\drumk\\\\source\\\\repos\\\\Satisfactory_Factory_Planner\\\\Satisfactory_Objects\\\\Recipes\\\\satisfactory_recipes.json\");
//Console.WriteLine(dataFile);
var JSONdata = JsonSerializer.Deserialize<List<Recipe>>(dataFile);
foreach(Recipe recipe in JSONdata)
{
Console.WriteLine(recipe);
}
}
}
正在导入数据,因为如果我使用 Console.WriteLine(dataFile);它完美地打印到控制台。但是 Deserialize 方法只是返回“Satisfactory_Objects.Recipes.Recipe”,而不是其中存储的数据。
我究竟做错了什么?
-
好吧,对于初学者来说,您的 JSON 字符串不是一个数组,它是一个具有数组值的对象。此外,内部数组与您的
Recipe类不匹配。 -
因为
Console.WriteLine(recipe)将简单地在recipe上调用ToString,并且由于您的Recipe类不会覆盖ToString方法,它将使用默认行为,即只返回完整的类型名称,即Satisfactory_Objects.Recipes.Recipe所以按预期工作。你真正想要打印什么? -
此外,反序列化它是行不通的。我建议您使用json2csharp 之类的工具(记得勾选“使用 Pascal Case”设置)来生成您需要的类的粗略大纲
-
正如@freakish 指出的那样,您的课程与json 不匹配。例如,\'Produces\' 不在 json 中,需要一个键值对。我假设应该是 \'ItemProduced\' 并期待一个字符串。 Resources 和 ByProducts 也有同样的情况,因为他们期望的类型与 json 中的类型不同。
-
谢谢各位,我会再回去检查一下格式。就像我说的那样,这是我第一次使用 JSON。当你说它不是数组时有点奇怪,这是否意味着我应该将它全部包含在 [] 中? MindSwipe 我试图做的是有一个配方结构,数据可以插入其中然后从那里处理。谢谢你的链接,我现在就去看看
标签: c# json system.text.json