Skip to content

Improve error message in scenaria where JsonIgnore is combined with required members. #92330

@grosch-intl

Description

@grosch-intl

Description

It's often necessary to use the required flag on a property that you don't want serialized via JSON. Adding the JsonIgnore attribute to such a property results in an InvalidOperationException.

Reproduction Steps

void Main() {
	var dto = new DTO {
		NotRequiredNumber = 1,
		Number = 2
	};
	
	JsonSerializer.Serialize<DTO>(dto);
}

class DTO {
	[JsonIgnore]
	public required int Number { get; init; }
	public int NotRequiredNumber { get; init; }
}

Expected behavior

Should be able to have the JSON generated without the ignored property.

Actual behavior

JsonPropertyInfo 'Number' defined in type 'UserQuery+DTO' is marked required but does not specify a setter.

Regression?

No

Known Workarounds

No response

Configuration

  • .NET 7
  • Windows 10
  • x64
  • Not specific to this configuration.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions