Closed
Description
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