使用ConfigurationBuilder时,Newtonsoft.Json属性不受尊重

时间:2017-09-22 18:37:18

标签: asp.net-core-2.0

Asp.Net Core 2.0中的ConfigurationBuilder正在使用Json.Net/Newtonsoft.Json来实现.AddJsonFile()功能。我在解析错误以及Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser的源代码中看到过它。但是,它忽略了我用来装饰我的属性的属性(例如JsonProperty)。

有没有办法让这种情况发生?

鉴于此example.json文件:

{
    "ExampleObjectSection": {
        "Prop": "Hello World!"
    }
}

......这个班级

class Example
{
    [JsonProperty(PropertyName = "Prop")]
    public string Property { get; set; }
}

...并且此代码:

static void Main(string[] args)
{
    IConfigurationRoot cfg = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("example.json", optional: false, reloadOnChange: true)
        .Build();
    Example e1 = cfg.GetSection("ExampleObjectSection").Get<Example>();
    // Here: e1.Property = null

    string str = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "example.json"));
    Example e2 = JsonConvert.DeserializeObject<Dictionary<string, Example>>(str)["ExampleObjectSection"];
    // Here: e2.Property = "Hello World!"
}

结果是

直接通过JsonConvert时,对象不会反序列化。

再次:可以使用正常的Newtonsoft反序列化功能吗?或者有新方法吗? (DataMember / DataContract属性似乎也没有做任何事情,但我真的没有去那个兔子洞。)

1 个答案:

答案 0 :(得分:1)

基于此答案Json - strongly - typed configuration配置不关心jsonproperty名称。

- 偏离主题的内容已被删除 -