JSON file parsing

Venkatesh H 0 Reputation points
2026-07-23T10:53:30.4466667+00:00

consider having different section in the JSON file , how to handle that problem

{

"connectionString":{

},

"SMTP":{

}

}

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


4 answers

Sort by: Most helpful
  1. Rudzani Mafela 0 Reputation points
    2026-07-24T05:36:37.32+00:00

    Hy @Venkatesh H In C# the common approach is to create a separate class for each configuration section and bind each section individually.

    For example, given this appsettings.json:

    {

    "ConnectionString": {

    "Server": "localhost",
    
    "Database": "MyDB",
    
    "User": "sa",
    
    "Password": "password123"
    

    },

    "SMTP": {

    "Host": "smtp.gmail.com",
    
    "Port": 587,
    
    "Username": "******@gmail.com",
    
    "Password": "smtpPassword"
    

    }

    }

    Create classes for each section:

    public class ConnectionStringSettings

    {

    public string Server { get; set; }
    
    public string Database { get; set; }
    
    public string User { get; set; }
    
    public string Password { get; set; }
    

    }

    public class SmtpSettings

    {

    public string Host { get; set; }
    
    public int Port { get; set; }
    
    public string Username { get; set; }
    
    public string Password { get; set; }
    

    }

    Then read each section:

    using Microsoft.Extensions.Configuration;

    IConfiguration configuration = new ConfigurationBuilder()

    .AddJsonFile("appsettings.json")
    
    .Build();
    

    var connectionSettings = configuration

    .GetSection("ConnectionString")
    
    .Get<ConnectionStringSettings>();
    

    var smtpSettings = configuration

    .GetSection("SMTP")
    
    .Get<SmtpSettings>();
    

    Alternatively, if you only need a single value:

    string server = configuration["ConnectionString:Server"];

    string smtpHost = configuration["SMTP:Host"];

    Was this answer helpful?

    0 comments No comments

  2. Nancy Vo (WICLOUD CORPORATION) 8,070 Reputation points Microsoft External Staff Moderator
    2026-07-24T03:35:24.4866667+00:00

    Hello @Venkatesh H ,

    Thanks for your question.

    Besides using the GetSection method, you can deserialize the JSON file directly. I recommend creating a class that matches your JSON sections and then using System.Text.Json.JsonSerializer to convert the file into an object:

    var myConfig = JsonSerializer.Deserialize<MyConfigClass>(jsonString);
    

    Alternatively, you can use JsonDocument to parse the text and read the sections manually:

    using JsonDocument doc = JsonDocument.Parse(jsonString);
    var smtpSection = doc.RootElement.GetProperty("SMTP");
    

    I hope this addresses your question. If this response was helpful, please consider following the guidance to provide feedback. Thank you.

    Was this answer helpful?


  3. Bruce (SqlWork.com) 84,856 Reputation points
    2026-07-23T14:45:26.2333333+00:00

    Assuming this is a config file, read the docs:

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0

    You are interested in GetSection.

    Was this answer helpful?

    0 comments No comments

  4. AgaveJoe 31,376 Reputation points
    2026-07-23T14:29:49.7966667+00:00

    Your question is missing context, which makes it difficult to provide a precise answer. Below is a basic example of reading a JSON file, deserializing its contents, and displaying the values on the console using two different approaches.

    config.json

    (Ensure this file is located in your application's output directory)

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
      },
      "SMTP": {
        "Server": "smtp.example.com",
        "Port": 587,
        "SenderEmail": "admin@example.com"
      }
    }
    

    Console Application Example

    using System;
    using System.IO;
    using System.Text.Json;
    using System.Text.Json.Nodes;
    class Program
    {
        static void Main()
        {
            string filePath = "config.json";
            // Ensure the file exists before attempting to read
            if (!File.Exists(filePath))
            {
                Console.WriteLine($"Configuration file not found: {filePath}");
                return;
            }
            // Read the raw JSON text directly from the file
            string jsonString = File.ReadAllText(filePath);
            // Approach 1: Deserialize into strongly typed classes
            var config = JsonSerializer.Deserialize<RootConfig>(jsonString);
            Console.WriteLine($"Connection: {config?.ConnectionString?.DefaultConnection}");
            Console.WriteLine($"SMTP Server: {config?.SMTP?.Server}:{config?.SMTP?.Port}");
            // Approach 2: Parse into a JsonNode for dynamic section navigation
            JsonNode rootNode = JsonNode.Parse(jsonString);
            string server = rootNode?["SMTP"]?["Server"]?.ToString();
            Console.WriteLine($"Extracted via JsonNode - SMTP Server: {server}");
        }
    }
    public class RootConfig
    {
        public ConnectionStringConfig ConnectionString { get; set; }
        public SmtpConfig SMTP { get; set; }
    }
    public class ConnectionStringConfig
    {
        public string DefaultConnection { get; set; }
    }
    public class SmtpConfig
    {
        public string Server { get; set; }
        public int Port { get; set; }
        public string SenderEmail { get; set; }
    }
    

    If you are building a .NET web application and are struggling with how .NET natively handles configuration files and dependency injection, please let us know. For more details on the native options pattern, see the official Microsoft Configuration Documentation.

    If this does not answer your question, please clarify what you are trying to accomplish by providing a minimal reproducible example, explaining how you expect the code to function, and detailing what is actually happening.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.