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.
System.Text.Json does not require or support “labeling” the element type inside a JSON array. The JSON produced by
[
{
"LastFileNum": 0,
"LastFolderNum": -1,
"Path": "C:\\Users\\William\\Pictures"
}
]
is already the correct representation for FolderStack<FolderState> (a stack of FolderState objects). The deserialization error is not because FolderState is unlabeled.
Key points and fixes:
- Array of objects is the correct shape
JsonSerializer.Deserialize<FolderStack<FolderState>>(...)expects a JSON array of objects whose properties matchFolderState. Extra properties in JSON are ignored by default; missing properties are allowed unless marked as required. There is no need for:
That is not valid JSON and will not be understood by[ FolderState: [ { ... } ] ]System.Text.Json. - Use the generated type info correctly
With source generation, the correct call for aFolderStack<FolderState>is:
When deserializing from a stream:// Serialize string jsonStr = JsonSerializer.Serialize( folderStateStack.FolderStack, SourceGenerationContext.Default.FolderStackFolderState); // Deserialize from string folderStateStack.FolderStack = JsonSerializer.Deserialize( jsonStr, SourceGenerationContext.Default.FolderStackFolderState);
The second parameter (using var fileStream = File.OpenRead(path); folderStateStack.FolderStack = JsonSerializer.Deserialize( fileStream, SourceGenerationContext.Default.FolderStackFolderState);FolderStackFolderState) is the generatedJsonTypeInfo<FolderStack<FolderState>>, which matches the JSON array ofFolderStateobjects. - Ensure the generic type is included in the context
The context already includes:
This is correct. No additional labeling is required in JSON.[JsonSerializable(typeof(FolderStack<FolderState>))] [JsonSerializable(typeof(FolderState))] internal partial class SourceGenerationContext : JsonSerializerContext { } - Check for other causes of the exception
SinceSystem.Text.Jsonignores unknown JSON properties and allows missing ones by default, the usual causes of exceptions here are:- The JSON is not valid (trailing commas, comments, or the “FolderState:” text).
- The stream is not positioned at the beginning (e.g., reused stream without
Position = 0). - A different type is being deserialized than the one registered in the context.
In summary, the JSON shape is already correct; remove any extra labels like FolderState: and ensure the deserialization uses SourceGenerationContext.Default.FolderStackFolderState against a valid JSON array.
References: