【问题标题】:How to load values via System.Text.Json from a file and store them readonly?如何通过 System.Text.Json 从文件中加载值并将它们只读存储?
【发布时间】:2020-01-29 20:00:59
【问题描述】:

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

到目前为止我的代码:

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

还有设置类:

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 需要能够访问设置器。

【问题讨论】:

标签: c# json readonly system.text.json


【解决方案1】:

使用公共set 为序列化程序创建一个基类,然后在不允许它们被变异的派生类中覆盖它们。


我建议您更改设计并创建一个所有属性都可变的基类,这将成为任何反序列化操作的目标(因为可变属性与反序列化配合得很好)。然后消费者将通过隐蔽/复制/反射从该基类获取不可变实例。

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

}

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多