【问题标题】:Take string value from appsetting.json and set it to JSON Key in c#从 appsetting.json 获取字符串值并将其设置为 c# 中的 JSON 键
【发布时间】:2020-02-03 06:05:23
【问题描述】:

我正在将 appsetting.json 中的密钥放入 c# 代码中。现在我必须捕获它并从 foreach 循环 c# 中的 JSON 响应中获取值

在 appsetting.Json 中: "CustomField": "customfield_10118"

以及我必须捕获值的代码:

【问题讨论】:

  • 你从这个 中究竟是什么意思“并从 foreach 循环 c# 中的 JSON 响应中获取值” 我在你的代码中没有看到 json 响应?也不要粘贴代码图片
  • @MichaelRandall,对于粘贴代码图像,我深表歉意。实际上。我已经使用了 appsetting.json 中的 CustomField,其值为 customfield_10118。现在循环它时 k.fields.customfield_10118 的值为“ABC”。现在我想把“ABC”变成epicKey。
  • @Vishvjitshinde k.fields 的数据类型是什么?你在那条线上遇到的错误是什么?请粘贴描述组合结构的代码。
  • 不要为粘贴代码图像而道歉——不要这样做。将其替换为您的代码作为文本。

标签: c# .net .net-core asp.net-core-mvc


【解决方案1】:

也许您需要indexer

因为我无法假设任何关于 k 的信息,但它由字段 idfields(均为未知类型)组成,并且当您尝试使用 string 变量作为键时,您要么需要 @ 987654327@ 为IDictionary<string, ...> 类型,或者您可以为fields 类提供索引器。

1) 字典:

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

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

2) 索引器

假设k 中的fieldsSomeClass 的类型。然后在SomeClass里面:

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

假设您将所有这些值存储在其他地方并且索引器只是从中获取它们的一种方式,以使此语法正确:

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

总结一下:

  • 如果fields 已经是定义良好的类并且您只需要添加对索引的支持或处理一些设置或获取值的自定义逻辑:使用索引器,
  • 在任何其他情况下 - 使用字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2019-08-26
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多