KEMBAR78
System.Text.Json source generator fails to deserialize init-only & required properties · Issue #58770 · dotnet/runtime · GitHub
Skip to content

System.Text.Json source generator fails to deserialize init-only & required properties #58770

@dallmair

Description

@dallmair

Description

When using the System.Text.Json source generator, init-only properties are not deserialized.

Repro code:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace JsonSerialization
{
	public static class Program
	{
		public static void Main()
		{
			const string json = @"{ ""InitOnly"": "".NET"", ""Settable"": ""Rocks"" }";

			var tagLine1 = JsonSerializer.Deserialize<TagLine>(json);
			Console.WriteLine(tagLine1.InitOnly ?? "tagLine1.InitOnly is null");
			Console.WriteLine(tagLine1.Settable ?? "tagLine1.Settable is null");

			Console.WriteLine();

			var tagLine2 = JsonSerializer.Deserialize<TagLine>(json, TagLineJsonContext.Default.TagLine);
			Console.WriteLine(tagLine2.InitOnly ?? "tagLine2.InitOnly is null");
			Console.WriteLine(tagLine2.Settable ?? "tagLine2.Settable is null");
		}
	}

	public sealed class TagLine
	{
		public string InitOnly { get; init; }   // This is always null when deserialized with TagLineJsonContext
		public string Settable { get; set; }
	}

	[JsonSerializable(typeof(TagLine), GenerationMode = JsonSourceGenerationMode.Metadata)]
	public partial class TagLineJsonContext : JsonSerializerContext
	{
	}
}

Expected output:

.NET
Rocks

.NET
Rocks

Actual output:

.NET
Rocks

tagLine2.InitOnly is null
Rocks

Configuration

  • .NET 5.0.9 with System.Text.Json version 6.0.0-preview.7.21377.19
  • Windows 10.0.19043.1052 x64

Metadata

Metadata

Labels

Cost:MWork that requires one engineer up to 2 weeksPriority:1Work that is critical for the release, but we could probably ship withoutarea-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionssource-generatorIndicates an issue with a source generator feature

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions