I'm trying to write a recipe parser in C#. I have tried using both Newtonsoft and System.Text.Json. I have used online json class builders and VS2019 Paste as json classes. I have got the Newtonsoft example code to run.
Schema.org Recipe https://schema.org/Recipe
Class I am using. I'm really only interested in these 2 values
public class Recipe
{
public string recipeIngredient { get; set; }
public string recipeInstructions { get; set; }
}
Code - this code runs with with no error.
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}");
}
Trying to read value. No error or value.
Console.WriteLine(recipe.recipeIngredient);
I'm not sure I understand how a schema.org document needs to be traversed. In the generated classes I can see Graph and Context which I'm guessing are root nodes. But my experiments suggest that I don't need all of the classes - just recipeIngredient and recipeInstructions. And this is only one recipe - I want to parse a list of recipes and I'm sure they'll all have their own classes so I'm looking for the most generalised way to get the 2 field values I'm seeking.
EDIT
Using tymtam's Json Document example I can see that there's an object there with
Console.WriteLine(recipes.Count);
But I can't get the values to display using
Console.WriteLine(recipes[0].Ingredients.ToString());
Console.WriteLine(recipes[0].Instructions.ToString());
I also tried to print ingredients with
foreach (var recipe in recipes)
{
Console.WriteLine(recipes[0].Ingredients);
}
But that only prints the object name and not the elements
System.Linq.Enumerable+WhereSelectEnumerableIterator
EDIT 2: SOLVED
foreach (var ingredient in recipes[0].Ingredients)
Console.WriteLine(ingredient);
foreach (var instruction in recipes[0].Instructions)
Console.WriteLine(instruction);