如何通过 System.Text.Json 从文件中加载值并以只读方式存储它们?

How to load values via System.Text.Json from a file and store them readonly?

我想通过 System.Text.Json 从 JSON 文件加载设置。 这些设置在加载后应该都是只读的。

到目前为止我的代码:

string jsonString = File.ReadAllText(filename);
Settings s = JsonSerializer.Deserialize<Settings>(jsonString);

和设置-class:

public class Settings
{
    public decimal A { get; set; }
    public int B { get; set; }
    public double C { get; set; }
    public double D { get; set; }
}

问题:值是可编辑的,使用 private set; 不起作用,因为 JsonSerializer 需要能够访问设置器。

为序列化器创建一个带有 public set 的基础 class,然后在派生的 class 中覆盖它们,这不允许它们被改变。


我建议您更改设计并制作一个所有属性都可变的基础 class,这将成为任何反序列化操作的目标(因为可变属性与反序列化).然后消费者将通过 covert/copy/reflect 从该基础 class.

获取不可变实例
var bse = JsonConvert.DeserializeObject<MutablePropertyStore>("{ 'PropertyB' : true }");
Console.WriteLine("Base:    " +  bse.ToString());   

var derived = new ImmutablePropertyStore(bse);              
Console.WriteLine("Derived: " + derived.ToString());    

结果

Base:    Property A is 'False' and Property B is 'True'.
Derived: Property A is 'False' and Property B is 'True'.

示例.Net Fiddle

代码

public sealed class ImmutablePropertyStore : MutablePropertyStore
{
    public new bool PropertyA { get; private set; }
    public new bool PropertyB { get; private set; }

    public ImmutablePropertyStore() { }

    public ImmutablePropertyStore(MutablePropertyStore ms)
    {
        PropertyA = ms.PropertyA;
        PropertyB = ms.PropertyB;
    }

    public ImmutablePropertyStore(bool propertyA = true, bool propertyB = false)
    {
        PropertyA = propertyA;
        PropertyB = propertyB;
    }

    public override string ToString() 
        => $"Property A is '{PropertyA}' and Property B is '{PropertyB}'."; 
}

public class MutablePropertyStore
{
    public virtual bool PropertyA { get; set;}
    public virtual bool PropertyB { get; set;}

    // Set all defaults here
    public MutablePropertyStore() {  }

    public override string ToString() 
        => $"Property A is '{PropertyA}' and Property B is '{PropertyB}'.";      

}