You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅允许在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:15:05