简体   繁体   English

将 appsettings.json 与 json 数组反序列化为 C# 列表

[英]Deserialize appsettings.json with json array into C# List

I have a C#.Net Core Console Application thats supposed to check different Logfiles if these contain Errors and notifies the right person via Email. The Application has an appsetting.json that looks like this:我有一个 C#.Net 核心控制台应用程序,如果这些日志文件包含错误,它应该检查不同的日志文件,并通过 Email 通知合适的人。该应用程序有一个 appsetting.json,如下所示:

{
  "Programs": [
    {
      "name": "program 1",
      "LoggingPath": "C:\...",
      "Emails": [
        "person1@company.com",
        "person2@company.com",
        "person3@company.com"
      ]
    },
    {
      "name": "program 2",
      "LoggingPath": "C:\...",
      "Emails": [
        "person1@company.com",
        "person2@company.com",
        "person3@company.com"
      ]
    }
  ]
}

Now i want to convert this Json into a C# Object List to iterate through the different Programs and do my Log analyzing etc.现在我想将此 Json 转换为 C# Object 列表以遍历不同的程序并进行日志分析等。

I used https://json2csharp.com to convert the Json into this C# Code:我使用https://json2csharp.com将 Json 转换为这个 C# 代码:

public class Program
{
    public string name { get; set; }
    public string LoggingPath { get; set; }
    public List<string> Emails { get; set; }
}

public class Root
{
    public List<Program> Programs { get; set; }
}

My code to initialize the appsettings.json and deserialization looks like this:我初始化 appsettings.json 和反序列化的代码如下所示:

public static void Main(string[] args)
{
    IConfiguration configuration;
    configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    JToken JtokenConfig = Serialize(configuration);

    Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(JtokenConfig.ToString());
}

But when I try this I get the following Error:但是当我尝试这样做时,出现以下错误:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[LogAnalyzer.Model+Program]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. Newtonsoft.Json.JsonSerializationException: '无法将当前的 JSON object(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[LogAnalyzer.Model+Program]' 因为该类型需要一个JSON 数组(例如 [1,2,3])以正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像 integer 这样的原始类型,不是像array or List),可以从 JSON object 反序列化。JsonObjectAttribute 也可以添加到类型以强制它从 JSON object 反序列化。

I can't change the Json to an array (Without the "Programs":) cause the appsettings.json builder requires an object and not an array.我无法将 Json 更改为数组(没有“程序”:),因为 appsettings.json 生成器需要 object 而不是数组。

I have also tried to use this Json to get rid of the array and use a dynamic C# property to deserialize the different object names but the deserialization also failed.我还尝试使用此 Json 摆脱数组并使用动态 C# 属性反序列化不同的 object 名称,但反序列化也失败了。

{
    "Programs": {
        "program 1": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        },
        "program 2": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        }
    }
}

I read countless stackoverflow threads and other websites but wasnt able to convert the Json into a C# List.我阅读了无数的 stackoverflow 线程和其他网站,但无法将 Json 转换为 C# 列表。

I hope someone here can help me or give me a hint.我希望这里有人可以帮助我或给我提示。

you can install Microsoft.Extensions.Configuration.Binder Nuget package and try this code您可以安装 Microsoft.Extensions.Configuration.Binder Nuget package 并尝试此代码

using Microsoft.Extensions.Configuration;

List<Program> programs = configuration.GetSection("Programs").Get<List<Program>>();

Update更新

the second json you can deserialize to a dictionary第二个 json 你可以反序列化为字典

Dictionary<string,Program> programsDict = configuration.GetSection("Programs")
                                     .Get<Dictionary<string,Program>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM