An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Hi @WoodManEXP ,
Your JSON is actually fine the way it is, and you don't need to label the elements. A FolderStack<FolderState> is just a stack of objects, so System.Text.Json correctly writes it as a plain array:
[
{ "LastFileNum": 0, "LastFolderNum": -1, "Path": "C:\\Users\\William\\Pictures" }
]
That [ "FolderState": [ ... ] ] shape you were considering isn't valid JSON, so don't go that route. The serializer matches the object properties by name on the way back in, so the array is exactly what it expects.
I reproduced your setup (the custom FolderStack<T> : Stack<T>, source generation, the same context) and deserializing from a string works perfectly. So the type and the markers aren't the problem.
What does throw is reusing the same FileStream for both writing and reading. After you serialize into the stream, its position is sitting at the end of the file. When you then call Deserialize on that same stream, there are no bytes left to read, and you get:
System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token...
That matches the exception you're hitting. Two ways to fix it:
// Rewind the existing stream before reading
fileStream.Position = 0;
FolderStack = JsonSerializer.Deserialize(fileStream, SourceGenerationContext.Default.FolderStackFolderState);
// Open a fresh read stream
using var readStream = File.OpenRead(path);
FolderStack = JsonSerializer.Deserialize(readStream, SourceGenerationContext.Default.FolderStackFolderState);
One more thing worth knowing, since it bites a lot of people: a stack round-trips in reversed order. If you push A then B, the JSON comes out as [B, A], but when you deserialize, the items get pushed back in that array order, so A ends up on top instead of B. If the original top-of-stack matters to you, either reverse the collection after loading, or store/load a List<FolderState> and rebuild the stack in the order you want.
Hope this helps! If my explanation and the information I provided were helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.