簡體   English   中英

如何訪問列表<object>來自 appsettings.Json?<div id="text_translate"><p> 在我的 appsettings.json 我有一個這樣的字段</p><pre> "MyFields": [ { "name":"one", "type":"type1" "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}] }, { "name":"two", "type":"type2"... .. and so on } ]</pre><p> 我制作了一個具有以下屬性的 class Myfield:</p><pre> public class MyField { [JsonProperty] public string? name { get; set; } [JsonProperty] public string? type { get; set; } [JsonProperty] public IDictionary<string,string>? parameters { get; set; } }</pre><p> 我正在嘗試使用配置在另一個 class 中訪問它,如下所示:</p><pre> //config is the configuration var myFields = config.GetSection("MyFields").Get<List<MyField>>();</pre><p> 問題是 myFields 結果是空的。 但是當我通過消除“參數”字段來做同樣的事情時,它就像一個魅力。</p><p> 我知道這與匹配不當有關,但能得到一些幫助會很棒。</p></div></object>

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

在我的 appsettings.json 我有一個這樣的字段


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

我制作了一個具有以下屬性的 class Myfield:


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

我正在嘗試使用配置在另一個 class 中訪問它,如下所示:


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

問題是 myFields 結果是空的。 但是當我通過消除“參數”字段來做同樣的事情時,它就像一個魅力。

我知道這與匹配不當有關,但能得到一些幫助會很棒。

你有一個錯誤,應該是

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

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

但也許這會更有效率

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM