简体   繁体   中英

How can I access a List<object> from appsettings.Json?

In my appsettings.json I have a field like this


    "MyFields" : [
    {
    "name":"one",
    "type":"type1"
    "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}]
    },
    {
    "name":"two",
    "type":"type2"
    ...
    ..
    and so on
    }
    ]

I have made a class Myfield with the following properties:


    public class MyField
        {
            [JsonProperty]
            public string? name { get; set; }
    
            [JsonProperty]
            public string? type { get; set; }
    
            [JsonProperty]
            public IDictionary<string,string>? parameters { get; set; }
        }

And I am trying to access it in an other class using the config, like this:


    //config is the configuration
       var myFields = config.GetSection("MyFields").Get<List<MyField>>();

the problem is that myFields turn out to be empty. But when I do the same thing by eliminating the "parameters" field then it works like a charm.

I know its something related to improper matching but it'll be great to get some help.

you have a bug, should be

    public Dictionary<string, string>[] parameters { get; set; }

     //or
    public  List<Dictionary<string, string>> parameters { get; set; }

but maybe this would be more effiecient

public  List<KeyValue> parameters { get; set; }
....

public class KeyValue
{
    public string key {get; set;}
    public string value {get; set;}
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM