C
C#•4w ago
KIRA BELMONT

Json Serializing And Deserializing Practice Errors

I am practicing Json Serializing rightnow, but I got stuck on this for the last day. I always get this error, and I just want 1 thing, save the ingredients, and load it.
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Cookie_Cookbook.Recipe.Ingredient
{
public static class IngredientManagement
{
public static void ShowCurrentRecipes(List<Ingredient> list)
{
if (list.Count == 0)
{
Console.WriteLine("There is no recipes added.");
}
else
{
Console.WriteLine("Recipe Added: ");
foreach (Ingredient recipe in list)
{
Console.WriteLine($"{recipe.Name}:{recipe.Instructions}");
}
}
}
public static void ShowIngredients()
{
Console.WriteLine("1. Wheat flour\n2. Coconut flour\n3. Butter\n4. Chocolate\n5. Sugar\n6. Cardamom\n7. Cinnamon\n8. Cocoa powder");
}
private static readonly string filePath = "recipe.json";
public static void Save(List<Ingredient> list)
{
string toJson = JsonSerializer.Serialize(list);
File.WriteAllText(filePath, toJson);
}
public static List<Ingredient> Load()
{
if (File.Exists(filePath))
{
string jsonData = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Ingredient>>(jsonData) ?? new List<Ingredient>();
}
return new List<Ingredient>();
}


}
}

System.NotSupportedException: 'Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'Cookie_Cookbook.Recipe.Ingredient.Ingredient'. Path: $[0] | LineNumber: 0 | BytePositionInLine: 2.'
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Cookie_Cookbook.Recipe.Ingredient
{
public static class IngredientManagement
{
public static void ShowCurrentRecipes(List<Ingredient> list)
{
if (list.Count == 0)
{
Console.WriteLine("There is no recipes added.");
}
else
{
Console.WriteLine("Recipe Added: ");
foreach (Ingredient recipe in list)
{
Console.WriteLine($"{recipe.Name}:{recipe.Instructions}");
}
}
}
public static void ShowIngredients()
{
Console.WriteLine("1. Wheat flour\n2. Coconut flour\n3. Butter\n4. Chocolate\n5. Sugar\n6. Cardamom\n7. Cinnamon\n8. Cocoa powder");
}
private static readonly string filePath = "recipe.json";
public static void Save(List<Ingredient> list)
{
string toJson = JsonSerializer.Serialize(list);
File.WriteAllText(filePath, toJson);
}
public static List<Ingredient> Load()
{
if (File.Exists(filePath))
{
string jsonData = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Ingredient>>(jsonData) ?? new List<Ingredient>();
}
return new List<Ingredient>();
}


}
}

System.NotSupportedException: 'Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'Cookie_Cookbook.Recipe.Ingredient.Ingredient'. Path: $[0] | LineNumber: 0 | BytePositionInLine: 2.'
38 Replies
KIRA BELMONT
KIRA BELMONTOP•4w ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cookie_Cookbook.Recipe.Ingredient
{
public abstract class Ingredient
{
public abstract string Name { get;}
public abstract int ID { get;}
public virtual string Instructions => "Add to other ingredients.";
public Ingredient()
{

}
}

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cookie_Cookbook.Recipe.Ingredient
{
public abstract class Ingredient
{
public abstract string Name { get;}
public abstract int ID { get;}
public virtual string Instructions => "Add to other ingredients.";
public Ingredient()
{

}
}

}
this is the Ingredient Class
jcotton42
jcotton42•4w ago
(you repasted IngredientManagement)
Angius
Angius•4w ago
Well, the error is quite clear
jcotton42
jcotton42•4w ago
The most direct solution to your problem is polymorphic serialization https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism
How to serialize properties of derived classes with System.Text.Jso...
Learn how to serialize polymorphic objects while serializing to and deserializing from JSON in .NET.
KIRA BELMONT
KIRA BELMONTOP•4w ago
is this intermediate thing or beginners? i need to get the basics of this first
jcotton42
jcotton42•4w ago
uh, intermediate i guess
Angius
Angius•4w ago
Intermediate I'd say
jcotton42
jcotton42•4w ago
but if you want to serialize derived types into JSON, that's what you have to do
KIRA BELMONT
KIRA BELMONTOP•4w ago
this Ingredient is a class that has 2 sub classes, and all other objects created will be from these 2, either inherits from Ingredient class or the other 2 sub classes that also inherit from Ingredient class will I find the solution here? because I want to understand the basics of Json serialization at least, like how to do it properly and what exactly does it need, what is a file path and why we use it and these stuff
Angius
Angius•4w ago
Either get rid of that inheritance structure, or do the polymorphic serialization
jcotton42
jcotton42•4w ago
Well, if you want to stick to the absolute basics, you'll need to drop the inheritance.
Angius
Angius•4w ago
Two options, really
KIRA BELMONT
KIRA BELMONTOP•4w ago
what do u mean
jcotton42
jcotton42•4w ago
Because with inheritance, you need to tell the JSON serializer your entire inheritance hierarchy up front. Otherwise it can't know what type the JSON represents when it comes time to deserialize. If you're asking it to deserialize as a base type.
KIRA BELMONT
KIRA BELMONTOP•4w ago
Is there a video that explains the basics of this?
GrabYourPitchforks
GrabYourPitchforks•4w ago
To cotton's point, consider that the deserializer is going to try doing something equivalent to this:
List<Ingredient> list = new List<Ingredient>();
list.Add(new Ingredient()); // <-- ERROR: cannot instantiate an abstract class
List<Ingredient> list = new List<Ingredient>();
list.Add(new Ingredient()); // <-- ERROR: cannot instantiate an abstract class
So you need to configure the deserializer to tell it the equivalent of "don't say new Ingredient(...). Say new MyDerivedClass(...) instead!" But polymorphism is something of an advanced topic when it comes to deserialization, which is why my earlier recommendation was to avoid it if there's any possible way for you to do so. For example, do you really need lots of derived types hanging off the Ingredient class? Can't you take Name, Id, Instructions as constructor parameters and just have a single data type?
KIRA BELMONT
KIRA BELMONTOP•4w ago
Not really, i was practicing inheriting and interfaces with a udemy course and they did the same, but they did not have to do the polymorphism serialaization Idk, i will send you how the program should be
GrabYourPitchforks
GrabYourPitchforks•4w ago
^^^ But if you really need to deserialize polymorphic classes, this link gives you all the details. The example at the very top of the document should get you started.
KIRA BELMONT
KIRA BELMONTOP•4w ago
Welcome To The Recipes Adder! Type The ID To Add The Recipe Type Any Key Else To Finish 1. Wheat flour 2. Coconut flour 3. Butter 4. Chocolate 5. Sugar 6. Cardamom 7. Cinnamon 8. Cocoa powder 1 Type The ID To Add An Ingredient 2 Type The ID To Add An Ingredient 3 Type The ID To Add An Ingredient Recipe Added: Wheat Flour:Sieve. Add to other ingredients. Coconut Flour:Sieve. Add to other ingredients. Butter:Melt on low heat. Add to other ingredients. Press any ket to close this is the output, but after that, I want it to load all the recipes I saved and print it at the start
jcotton42
jcotton42•4w ago
What necessitates the use of inheritance there?
Angius
Angius•4w ago
Not sure why any inheritance is involved here tbh
KIRA BELMONT
KIRA BELMONTOP•4w ago
cmon guys =( so what, should i just avoid this assignment and go to the next section or what?
jcotton42
jcotton42•4w ago
Does the assignment require mixing JSON and inheritance?
KIRA BELMONT
KIRA BELMONTOP•4w ago
becuase i want to know how to save and load stuff later
Angius
Angius•4w ago
You're saying everything I want to say just a split second before me :KEKW:
KIRA BELMONT
KIRA BELMONTOP•4w ago
yes, but as I said in the video didn't have any problem with that, she went with a different aproach so this could be the reason but the problem is, she didn't even explain how to do it properly, just a brief introduction to Json and boom, do the assignment
GrabYourPitchforks
GrabYourPitchforks•4w ago
I'll say: it is very uncommon to mix serialization + inheritance. It really is an advanced scenario. Which is why we're all perplexed as to why you're stating both that you've never worked with this type of serialization before and that you have to use inheritance. Like, you jumped straight to a 300-level concept without going through 100-level or 200-level introductions.
KIRA BELMONT
KIRA BELMONTOP•4w ago
I guess that's why I was setting all day trying to figure it out😂
GrabYourPitchforks
GrabYourPitchforks•4w ago
Hah 🙂
Angius
Angius•4w ago
If the assignment doesn't have you serialize those recipes, don't serialize them Better yet: make your own version, on the side
KIRA BELMONT
KIRA BELMONTOP•4w ago
maybe talked with gpt for 3 hours and still not that much
Angius
Angius•4w ago
Without inheritance and with serialization
GrabYourPitchforks
GrabYourPitchforks•4w ago
Don't take it as a personal failing! It's just that you've taken on an advanced challenge.
Angius
Angius•4w ago
Try to figure it out, based on what you know, but without the limitations imposed by the course
GrabYourPitchforks
GrabYourPitchforks•4w ago
Try it with very simple data types first. Change the Ingredient class just to have very simple get/set properties. And go from there.
KIRA BELMONT
KIRA BELMONTOP•4w ago
but the thing is, I want to learn how to serialize because I want to make a small project that takes inputs and saves it, and have an option to show the thigns I saved with all of it's properties and what I really hate is that this is literally the last thing on the assignment so the moment i solve this I will be finished from it i just need to make the program save it and then print it
Angius
Angius•4w ago
Make this project, then And learn serialization while making it Learning by doing FTW
KIRA BELMONT
KIRA BELMONTOP•4w ago
this is what i get when i works Welcome To The Recipes Adder! Type The ID To Add The Recipe Type Any Key Else To Finish 1. Wheat flour 2. Coconut flour 3. Butter 4. Chocolate 5. Sugar 6. Cardamom 7. Cinnamon 8. Cocoa powder 0 Recipe Added: :Add to other ingredients. :Add to other ingredients. :Add to other ingredients. :Add to other ingredients. :Add to other ingredients. :Add to other ingredients. :Add to other ingredients. Press any ket to close why is this happening

Did you find this page helpful?