ShadowWulf
ShadowWulf

Reputation: 1

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:

{
  "Programs": [
    {
      "name": "program 1",
      "LoggingPath": "C:\...",
      "Emails": [
        "[email protected]",
        "[email protected]",
        "[email protected]"
      ]
    },
    {
      "name": "program 2",
      "LoggingPath": "C:\...",
      "Emails": [
        "[email protected]",
        "[email protected]",
        "[email protected]"
      ]
    }
  ]
}

Now i want to convert this Json into a C# Object List to iterate through the different Programs and do my Log analyzing etc.

I used https://json2csharp.com to convert the Json into this C# Code:

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:

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 (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LogAnalyzer.Model+Program]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. 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.

I can't change the Json to an array (Without the "Programs":) cause the appsettings.json builder requires an object and not an array.

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.

{
    "Programs": {
        "program 1": {
            "LoggingPath": "test",
            "Emails": [
                "[email protected]",
                "[email protected]",
                "[email protected]"
            ]
        },
        "program 2": {
            "LoggingPath": "test",
            "Emails": [
                "[email protected]",
                "[email protected]",
                "[email protected]"
            ]
        }
    }
}

I read countless stackoverflow threads and other websites but wasnt able to convert the Json into a C# List.

I hope someone here can help me or give me a hint.

Upvotes: 0

Views: 1390

Answers (2)

heyyy
heyyy

Reputation: 83

Update for .Net 8 You can deserialize automatically to custom types without using JsonSerializer or similar. My custom type here is corpus_g. My Json is corpora: [{corpus_g object}]

return _configuration
.GetSection("gemini_api")
.GetSection("corpora")
.Get<corpus_g[]>().FirstOrDefault();//

Upvotes: 0

Serge
Serge

Reputation: 43880

you can install Microsoft.Extensions.Configuration.Binder Nuget package and try this code

using Microsoft.Extensions.Configuration;

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

Update

the second json you can deserialize to a dictionary

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

Upvotes: 4

Related Questions