【发布时间】: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