我如何从appsettings.json获取json?

时间:2018-05-14 06:42:43

标签: c# json visual-studio-code

如何使用Microsoft.Extensions.Configuration获取appsettings.json数据? 我的appsettings.json文件是:

"Test": [
  {
    "A": "101",
    "B": "6390"
  },
  {
    "A": "101",
    "B": "6391"
  },
  {
    "A": "101",
    "B": "6392"
  }
]

何时使用

Configuration.GetSection("Test").GetChildren()

我收到错误:

System.Linq.Enumerable+SelectEnumerableIterator`2[System.String.Microsoft.Extensions.Configuration.IConfigurationSection]

我无法理解如何处理此错误。请询问是否需要任何信息。 问题不是重复,因为我无法正确运行代码,它会停止调试并给出我提到的错误。

哦,实际错误(如控制台所示)是:

  

未捕获的SyntaxError:无效或意外的令牌

2 个答案:

答案 0 :(得分:0)

考虑到您提供的微小信息,也许您只是输入错字。

IIRC,appsettings.json文件需要在根范围内有一个j-object。也许一个j阵列没问题。我不记得了。但你拥有的是一对键值对。一片对象。大多数JSON解析器都会在这样的输入上失败。请尝试在json文件中的所有文本周围添加括号{}:

{   //<--- added
  "Test": [
    {
      "A": "101",
      "B": "6390"
    },
    ....
  ]
}   //<--- added

答案 1 :(得分:0)

首先要做的是更改你的json并添加括号:

{
  "Test": [
      {
        "A": "101",
        "B": "6390"
      },
      {
        "A": "101",
        "B": "6391"
      },
      {
        "A": "101",
        "B": "6392"
      }
  ]
}

在使用IConfiguration读取设置之前,请添加以下参考,您可以使用nuget数据包管理器执行此操作:

enter image description here

您可以执行以下操作:

 // This class can be used for managing your AppSettings file.
class AppSettings
{
    private readonly IConfiguration configuration;

    public AppSettings(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    // Get the value at an specific key.
    public string GetValue(string key)
    {
        return configuration[key];
    }
}

class Program
{
    // This can be used for getting an configuration builder for your config file. Pass in the config name.
    public static IConfigurationBuilder LoadConfiguration(string configFileName)
    {
        // get the file from the current directory and create an builder from it.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
            .AddJsonFile(configFileName);

        return builder;

    }

    static void Main(string[] args)
    {
        // create configuration builder.
        var configuration = LoadConfiguration("appsettings.json");

        // create your AppSettings class and pass the IConfiguration object.
        AppSettings appConfig = new AppSettings(configuration.Build());

        // read the value.
        var firstItemAValue = appConfig.GetValue("Test:0:A");
        var secondItemBValue = appConfig.GetValue("Test:1:B");

    }
}