简体   繁体   中英

Take string value from appsetting.json and set it to JSON Key in c#

I am taking the key from appsetting.json into c# code. Now I have to capture that and get the value from JSON Response in foreach loop c#

In appsetting.Json: "CustomField": "customfield_10118"

and code where i have to capture the value:

在此处输入图片说明

Maybe You are in need of indexer ?

As I cannot assume anything about k but it consists of fields id and fields (both unknown type) and as You are trying to use a string variable as a key You would either need the fields to be of type IDictionary<string, ...> or You can provide an indexer for the class of fields .

1) Dictionary:

k.fields = new Dictionary<string, string>();

...
string CustomField = ...;
epicKey = k.fields[CustomField]

2) Indexer

Let assume that fields inside k is a type of SomeClass . Then inside SomeClass :

public class SomeClass
{
  ...
  public string this[string key] {
    get {
      return ...
    }
    set {
      ...
    }
  }
}

assuming that You are storing all those values somewhere else and indexer is only a way to get them from it, to make this syntax proper:

string CustomField = ...;
epicKey = k.fields[CustomField]

To summarise:

  • if fields is already well defined class and You just need to add a support of indexing or handle some custom logic of setting or getting values: use indexer,
  • in any other case - use dictionary.

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