【问题标题】:Newtonsoft.Json attributes not respected when using ConfigurationBuilder [duplicate]使用 ConfigurationBuilder 时不尊重 Newtonsoft.Json 属性 [重复]
【发布时间】:2018-03-04 10:00:35
【问题描述】:

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 属性似乎也没有做任何事情,但我真的没有进入那个兔子洞。)

【问题讨论】:

  • 那个question没有,但它是answer---3年前在下面的答案中链接---有。
  • 是的,我想指出另一个线程,因为这里的答案除了指向另一个答案的链接之外没有任何贡献。但是你的问题最好找到(我刚遇到同样的问题),所以我们绝对应该把它作为路标。这样,未来可能针对同一问题的解决方案将定向到单个线程。

标签: asp.net-core-2.0


【解决方案1】:

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

-- 离题内容已被删除 --

【讨论】:

  • 第一句和参考链接回答了问题(证实了我在源代码中找到的);谢谢!其余的都是题外话。
猜你喜欢
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多