使用Microsoft.Extensions.Configuration从appsettings.json获取对象列表;

时间:2017-05-23 22:24:45

标签: c# json configuration asp.net-core

我希望使用Microsoft.Extensions.Configuration解析来自asp.net核心项目appsetting.json的对象列表。这是我尝试过的。但我得到的结果为null。我做错了什么或不支持?

using Xunit;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Configuration.Test;

namespace Tests
{
    public class ConfigTests
    {
        [Fact]
        public void Test1()
        {
            string json = @"{
                                'Logging':  {
                                    'IncludeScopes':  false,
                                        'LogLevel':  {
                                            'Default':  'Warning'
                                        }
                                },

                                'other': 'blah',
                                'boxes': [
                                    {
                                        'id': '1',
                                        'code': '1234'
                                    },
                                    {
                                        'id': '2',
                                        'code': '0001'
                                    },
                                    {
                                        'id': '3',
                                        'code': '5678'
                                    }
                                ]
                            }";

            var configurationBuilder = new ConfigurationBuilder();
            var jsonConfigSource1 = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json) };

            configurationBuilder.Add(jsonConfigSource1);
            var Configuration = configurationBuilder.Build();

            var section = Configuration.GetSection("boxes");
            Boxes result = section.Get<Boxes>();
        }

        public class Boxes
        {
            public List<Box> boxes;
        }

        public class Box
        {
            public string id;
            public string code;
        }
    }
}

0 个答案:

没有答案