如何仅允许在JsonProperty反序列化时设置属性?求最优方案
Absolutely! Your current approach with the _processing flag gets the job done, but both Newtonsoft.Json (the go-to JSON library for traditional .NET) and System.Text.Json (the built-in serializer for .NET Core/.NET 5+) have native, cleaner ways to handle this "deserialize-only, then read-only" scenario without custom flag logic.
Option 1: For Newtonsoft.Json (Json.NET)
Instead of managing a _processing variable, you can make the property's setter private while keeping the [JsonProperty] attribute. Json.NET automatically uses reflection to access private setters during deserialization, but external code won’t be able to modify the property afterward:
private string _id; [JsonProperty(PropertyName = "id")] public string Id { get { return _id; } private set { _id = value; } }
This leverages the library’s built-in support for non-public members when explicitly marked with [JsonProperty], making your code simpler and less error-prone.
Option 2: For System.Text.Json (Built-in .NET Serializer)
If you’re using the newer built-in serializer, take advantage of C# 9.0+ init-only properties. These properties can only be set during object initialization (which includes deserialization) and become strictly read-only afterward—no backing field required:
using System.Text.Json.Serialization; [JsonPropertyName("id")] public string Id { get; init; }
The compiler enforces this read-only behavior, so you don’t have to worry about accidental modifications in your code after deserialization.
Both approaches eliminate the need for the _processing flag entirely, relying on established library or language features to keep your code clean and maintainable.
内容的提问来源于stack exchange,提问作者Ryan Detzel

