【发布时间】:2021-07-09 02:55:26
【问题描述】:
我正在尝试用 C# 编写一个食谱解析器。我尝试过同时使用 Newtonsoft 和 System.Text.Json。我使用了在线 json 类构建器和 VS2019 Paste 作为 json 类。我已经运行了 Newtonsoft 示例代码。
Schema.org 食谱https://schema.org/Recipe
我正在使用的课程。我真的只对这两个值感兴趣
public class Recipe
{
public string recipeIngredient { get; set; }
public string recipeInstructions { get; set; }
}
代码 - 此代码运行时没有错误。
var document = File.ReadAllText(@"D:\recipeExample.json");
Recipe recipe = null;
try
{
recipe = System.Text.Json.JsonSerializer.Deserialize<Recipe>(document);
}
catch (System.Text.Json.JsonException ex)
{
Console.WriteLine($"Error parsing : {ex}");
}
试图读取值。没有错误或价值。
Console.WriteLine(recipe.recipeIngredient);
我不确定我是否了解如何遍历 schema.org 文档。在生成的类中,我可以看到 Graph 和 Context 我猜是根节点。但是我的实验表明我不需要所有的类——只需要 recipeIngredient 和 recipeInstructions。 这只是一个食谱 - 我想解析一个食谱列表,我相信它们都会有自己的类,所以我正在寻找最通用的方法来获取我正在寻找的 2 个字段值。
编辑
使用 tymtam 的 Json Document 示例,我可以看到那里有一个对象
Console.WriteLine(recipes.Count);
但我无法获取要显示的值
Console.WriteLine(recipes[0].Ingredients.ToString());
Console.WriteLine(recipes[0].Instructions.ToString());
我也尝试用
打印成分foreach (var recipe in recipes)
{
Console.WriteLine(recipes[0].Ingredients);
}
但这只会打印对象名称而不是元素
System.Linq.Enumerable+WhereSelectEnumerableIterator
编辑 2:已解决
foreach (var ingredient in recipes[0].Ingredients)
Console.WriteLine(ingredient);
foreach (var instruction in recipes[0].Instructions)
Console.WriteLine(instruction);
【问题讨论】:
-
能否提供json文件的内容?
-
一种可能性是配方被一个额外的对象包裹。
{ "Recipe" : {.... -
抱歉没有看到您的评论 - 这是文件drive.google.com/file/d/1wS-CnbPjyi6N77WB0TxEVrUsTQypR2q3/…
标签: c# json parsing json.net system.text.json