My Dto has Id
property:
public class ADto
{
public int Id { get; set; }
public string Text { get; set; }
}
The Id
is set by EF Core not by Frontend request, so I want to ignore it on deserialization ( but do not ignore on serialization, so already set Id by EF Core will be returned to Frontend), how to achieve that with attributes? I am using using System.Text.Json.Serialization;
.
3
Answers
You can use the
JsonIgnore
attribute from System.Text.Json.Serialization. This attribute allows you to specify that a property should be ignored during the deserialization process but included during serialization.There is no way to achieve exactly what you want with the attributes built in to System.Text.Json as of .NET 8 or earlier.
As a workaround, in .NET 7 and later you could create a custom attribute, then check for it in a custom typeInfo modifier when generating contracts for your types.
First define the following attribute:
And modify your type as follows:
Then, when setting up your serialization options, apply the modifier in .NET 8 by calling
WithAddedModifier()
like so:Demo fiddle #1 here.
Notes:
The extension method
WithAddedModifier()
is new in .NET 8 and allows for modification of contracts of arbitraryIJsonTypeInfoResolver
instances, including both bothDefaultJsonTypeInfoResolver
andJsonSerializerContext
.In .NET 7, use
DefaultJsonTypeInfoResolver
and set the modifier explicitly:Demo fiddle #2 here.
.NET 8 also has the ability to serialize properties that are entirely nonpublic, so you could consider modifying
ADto
by markingId
with[JsonIgnore]
and adding a private get-only surrogate property like so:In .NET 7 and earlier the surrogate property would need to be public, which you probably would not want.
Demo fiddle #3 here.
How about this approach, without attributes, simple and clear: