1

The ConfigurationBuilder in Asp.Net Core 2.0 is using Json.Net/Newtonsoft.Json under the hood for the .AddJsonFile() functionality. I've seen it referenced in parsing errors as well as in the source for Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser. However, it's ignoring the Attributes I'm used to decorating my properties with (e.g. JsonProperty).

Is there a way to get that to happen?

Given this example.json file:

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

...this class

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

...and this code:

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!"
}

The result is that

The object isn't deserialized as it is when going directly through JsonConvert.

Again: Can normal Newtonsoft deserialization functionality be used? Or is there a new way to do this? (DataMember/DataContract attributes didn't seem to do anything either, but I really didn't go down that rabbit hole.)

2
  • That question does not, but it's answer---linked 3 years ago in the answer below---does. Commented Oct 16, 2020 at 15:06
  • Yeah, I wanted to point to the other thread, since the answer here does not contribute anything but a link to the other answer. But your question is better to find (I just encountered the same problem), so we should definitely leave it as a signpost. This way possible future solutions for the same problem are directed to a single thread. Commented Oct 16, 2020 at 15:07

1 Answer 1

0

Based on this answer Json - strongly - typed configuration Configuration does not care about jsonproperty name.

-- off-topic content has been removed --

Sign up to request clarification or add additional context in comments.

1 Comment

The first sentence and reference link answers the question (confirms what I found in the source code); thanks! The rest of it is off-topic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.