1

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.

4
  • I think this may be due to attempting to serialize an IConfiguration object. Is there a reason you are doing this vs reading the file itself as a string and deserializing that? The reason I say this is because, appsetting.json will always be present in a .NET (core) solution, its reasonable to assume that you are guaranteed to be able to find this file Commented Jan 17, 2023 at 15:06
  • Try this: var root = new Root(); configuration.Bind(root); Commented Jan 17, 2023 at 15:15
  • 1
    @Narish I created a new json file with the exact same content and tried this and it worked. Commented Jan 17, 2023 at 15:16
  • @ShadowWulf that's good to hear. Your models are correct, so deserialization should go without a problem, assume it has the proper source. Passing it the IConfiguration object may not guarantee that it finds the file itself, hence why reading the file directly and deserializing its contents that way would be a much safer bet Commented Jan 17, 2023 at 15:38

2 Answers 2

5

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>>();
Sign up to request clarification or add additional context in comments.

1 Comment

Will try that later. Thanks for the tips :)
0

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();//

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.