简体   繁体   English

如何通过 System.Text.Json 从文件加载值并将它们存储为只读?

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

I want to load settings from a JSON-file via System.Text.Json.我想通过 System.Text.Json 从 JSON 文件加载设置。 These settings should all be readonly after being loaded.这些设置在加载后都应该是只读的。

My code so far:到目前为止我的代码:

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

And the Settings-class:和设置类:

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

The problem: The values are editable and using private set;问题:值是可编辑的并使用private set; does not work because JsonSerializer needs to be able to access the setters.不起作用,因为 JsonSerializer 需要能够访问 setter。

Create a base class with public set for the serializer and then override them in derived class which does does not allow them to be mutated.为序列化程序创建一个带有公共set的基类,然后在不允许对其进行变异的派生类中覆盖它们。


I suggest that you change design and make a base class with all the properties mutable and that will be the target of any deserialization operation ( since mutable properties play well with deserialization ).我建议您更改设计并创建一个具有所有可变属性的基类,这将成为任何反序列化操作的目标(因为可变属性与反序列化配合得很好)。 Then a consumer will get the immutable instance via covert/copy/reflect it from that base class.然后消费者将通过从该基类中隐蔽/复制/反射它来获取不可变实例。

var bse = JsonConvert.DeserializeObject<MutablePropertyStore>("{ 'PropertyB' : true }");
Console.WriteLine("Base:    " +  bse.ToString());   

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

Result结果

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

Example .Net Fiddle示例.Net Fiddle

Code代码

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}'.";      

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM