0

I am using Microsoft.Extensions.Config.Json to bind some JSON configuration data to a class.

The class looks like this:

public class MyOptions {
    public string BuilderName { get; set; }
    public IDictionary<string, object> BuilderParameters { get; set; }
}

The binding code:

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

MyOptions options = new MyOptions();
config.Bind("MyOptions", options);

This all works fine as long as the JSON values are simple types such as strings, ints or bools. For example:

"MyOptions": [
    "BuilderName": "Test"
    "BuildParameters": {
        "A": true,
        "B": "Test"
    }
]

However, if the JSON contains an array, the binding totally fails and I just get a null instance:

"MyOptions": [
    "BuilderName": "Test"
    "BuildParameters": {
        "A": true,
        "B": [ "Test1", "Test2" ]
    }
]

I can't see why this would fail. I could use a comma-separated string or something that is then parsed to create an array within my code but it seems like that should be unnecessary. Certainly it's something I'd rather avoid if possible.

Edit:

One suggested solution is this: How to serialize a Dictionary as part of its parent object using Json.Net

This shows how to convert a group of JSON key/value pairs into a Dictionary. What I need is to do that where the value in one or more of the key/value pairs is a JSON array and it's a going into a Dictionary.

I expect the array to be converted to a collection (array, list, doesn't matter) of strings or objects.

Steve
  • 1,266
  • 16
  • 37
  • 1
    Does this answer your question? [How to serialize a Dictionary as part of its parent object using Json.Net](https://stackoverflow.com/questions/14893614/how-to-serialize-a-dictionary-as-part-of-its-parent-object-using-json-net) – oleksa Mar 18 '20 at 11:31
  • Why do you need `[ "Test" ]` instead of `"Test"` anyways? Its just a singleton JSON array. – RoadRunner Mar 18 '20 at 12:28
  • @oleksa No, that's serialisation. I need deserialisation. @RoadRunner It's an example. Perhaps it would be clearer if I changed it to `"B": [ "Test1", "Test2" ]` – Steve Mar 18 '20 at 14:48

0 Answers0