Skip to content

System.Text.Json code generator generates invalid code when Json property contains a dash #57836

@Jericho

Description

@Jericho

I have a class that contains the following property:

[JsonPropertyName("smtp-id")]
public string SmtpId { get; set; }

The code generator generates the following line in MyLibrary.PropertyNames.g.cs:

private static global::System.Text.Json.JsonEncodedText smtp-idPropName = global::System.Text.Json.JsonEncodedText.Encode("smtp-id");

Notice smtp-idPropName. This results in the following errors (and of course prevents my library from being compiled:

CS1026	) expected	MyLibrary (net5.0)	D:\_build\MyLibrary\Source\MyLibrary\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyJsonSerializerContext.PropertyNames.g.cs	264	Active
CS1002	; expected	MyLibrary (net5.0)	D:\_build\MyLibrary\Source\MyLibrary\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyJsonSerializerContext.PropertyNames.g.cs	264	Active

When I scroll down a little further in the "Error List" window, I notice another related error:

CS1519	Invalid token '"smtp-id"' in class, record, struct, or interface member declaration	MyLibrary (net5.0)	D:\_build\MyLibrary\Source\MyLibrary\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyJsonSerializerContext.PropertyNames.g.cs	264	Active

My library parses Json from a 3rd party API therefore I can't simply change the name of this property. I have to match the content of their Json which indeed contains a property with a dash.

❯ dotnet --info
.NET SDK (reflecting any global.json):
Version: 5.0.400

Runtime Environment:
OS Name: Windows
OS Version: 10.0.22000
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\5.0.400\

Host (useful for support):
Version: 6.0.0-preview.7.21377.19

.NET SDKs installed:
2.1.816 [C:\Program Files\dotnet\sdk]
3.1.302 [C:\Program Files\dotnet\sdk]
3.1.400 [C:\Program Files\dotnet\sdk]
3.1.411 [C:\Program Files\dotnet\sdk]
5.0.103 [C:\Program Files\dotnet\sdk]
5.0.104 [C:\Program Files\dotnet\sdk]
5.0.205 [C:\Program Files\dotnet\sdk]
5.0.302 [C:\Program Files\dotnet\sdk]
5.0.400 [C:\Program Files\dotnet\sdk]
6.0.100-preview.7.21379.14 [C:\Program Files\dotnet\sdk]

Microsoft Visual Studio Community 2019
Version 16.11.1
VisualStudio.16.Release/16.11.1+31613.86
Microsoft .NET Framework
Version 4.8.04161

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions