Skip to content

[API Proposal]: Extend JsonIgnoreCondition #66490

@WeihanLi

Description

@WeihanLi

Background and motivation

Sometimes we may want to ignore some properties only when serialize, included when deserialize, currently, we had JsonIgnoreCondition

public enum JsonIgnoreCondition
{
  Never,
  Always,
  WhenWritingDefault,
  WhenWritingNull,
}

Maybe we could add new conditions like WhenWriting/WhenReading(or WhenSerializing/WhenDeserializing ...)

API Proposal

edited

namespace System.Text.Json.Serialization;

public enum JsonIgnoreCondition
{
  Never = 0,
  Always = 1,
  WhenWritingDefault = 2,
  WhenWritingNull = 3,
+ WhenWriting = 4,
+ WhenReading = 5,
}

API Usage

public class TestModel
{  
  [JsonIgnore(Condition = JsonIgnoreCondition.WhenReading)]
  public int Age { get; set; }
  [JsonIgnore(Condition = JsonIgnoreCondition.WhenWriting)]
  public string Name { get; set; }
}

var json = JsonSerializer.Serialize(new TestModel{ Age = 10, Name="Mike" });
Assert.Equal("{\"Age\":10}", json);

json = "{\"Age\":10, \"Name\":\"Mike\"}";
var model = JsonSerializer.Deserialize<TestModel>(json);
Assert.Equal("Mike", model.Name);
Assert.Equal(0, model.Age);

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Text.Jsonhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions