Deserialize nested JSON into C# class

Deserialize nested JSON into C# class

To deserialize nested JSON into a C# class, you can use the System.Text.Json or Newtonsoft.Json library, both of which provide powerful JSON parsing capabilities. Here's an example using Newtonsoft.Json:

Let's say you have the following nested JSON:

{ "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "Anytown", "zip": "12345" } } 

You can create C# classes to represent this JSON structure:

using System; public class Address { public string Street { get; set; } public string City { get; set; } public string Zip { get; set; } } public class Person { public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } } 

Then, you can use Newtonsoft.Json to deserialize the JSON string into an instance of the Person class:

using Newtonsoft.Json; class Program { static void Main() { string json = @"{ ""name"": ""John Doe"", ""age"": 30, ""address"": { ""street"": ""123 Main St"", ""city"": ""Anytown"", ""zip"": ""12345"" } }"; Person person = JsonConvert.DeserializeObject<Person>(json); Console.WriteLine($"Name: {person.Name}"); Console.WriteLine($"Age: {person.Age}"); Console.WriteLine($"Address: {person.Address.Street}, {person.Address.City}, {person.Address.Zip}"); } } 

This will output:

Name: John Doe Age: 30 Address: 123 Main St, Anytown, 12345 

If you prefer to use System.Text.Json, the process is similar but with different classes (JsonSerializer and JsonSerializerOptions). The principle remains the same: define C# classes that mirror the structure of your JSON, then use the appropriate library to deserialize the JSON into instances of those classes.

Examples

  1. Deserialize Simple Nested JSON into C# Classes

    • Description: This code snippet shows how to deserialize a simple nested JSON structure into corresponding C# classes.
    • Code:
      using System.Text.Json; public class Address { public string Street { get; set; } public string City { get; set; } } public class Person { public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } // Nested object } string json = @"{ ""Name"": ""John"", ""Age"": 30, ""Address"": { ""Street"": ""123 Main St"", ""City"": ""Springfield"" } }"; Person person = JsonSerializer.Deserialize<Person>(json); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.Address.City}"); 
  2. Deserialize Nested JSON with Arrays in C#

    • Description: This snippet demonstrates how to deserialize nested JSON containing arrays into C# classes.
    • Code:
      using System.Text.Json; public class Company { public string Name { get; set; } public List<Person> Employees { get; set; } // Nested array } string json = @"{ ""Name"": ""Tech Corp"", ""Employees"": [ { ""Name"": ""Alice"", ""Age"": 28 }, { ""Name"": ""Bob"", ""Age"": 35 } ] }"; Company company = JsonSerializer.Deserialize<Company>(json); Console.WriteLine($"Company: {company.Name}, Employee Count: {company.Employees.Count}"); 
  3. Deserialize JSON with Optional Nested Objects in C#

    • Description: This code snippet demonstrates how to handle optional nested objects when deserializing JSON in C#.
    • Code:
      using System.Text.Json; public class Order { public string OrderId { get; set; } public string ProductName { get; set; } public Customer Customer { get; set; } // Optional nested object } public class Customer { public string Name { get; set; } public string Email { get; set; } } string json = @"{ ""OrderId"": ""12345"", ""ProductName"": ""Laptop"", ""Customer"": { ""Name"": ""John Doe"", ""Email"": ""john.doe@example.com"" } }"; Order order = JsonSerializer.Deserialize<Order>(json); Console.WriteLine($"Order ID: {order.OrderId}, Customer Name: {order.Customer?.Name}"); 
  4. Deserialize Nested JSON with Date-Time Fields in C#

    • Description: This query demonstrates how to deserialize nested JSON that contains date-time fields into C# classes.
    • Code:
      using System; using System.Text.Json; public class Event { public string Title { get; set; } public DateTime EventDate { get; set; } // Date-time field } string json = @"{ ""Title"": ""Annual Meeting"", ""EventDate"": ""2024-05-01T14:30:00"" }"; Event myEvent = JsonSerializer.Deserialize<Event>(json); Console.WriteLine($"Event Title: {myEvent.Title}, Date: {myEvent.EventDate}"); 
  5. Deserialize Deeply Nested JSON into C# Classes

    • Description: This snippet shows how to handle deeply nested JSON structures when deserializing into C# classes.
    • Code:
      using System.Text.Json; public class Engine { public int Horsepower { get; set; } public string Type { get; set; } } public class Car { public string Model { get; set; } public Engine Engine { get; set; } // Nested object } public class Garage { public List<Car> Cars { get; set; } // Nested array } string json = @"{ ""Cars"": [ { ""Model"": ""Sedan"", ""Engine"": { ""Horsepower"": 200, ""Type"": ""V6"" } }, { ""Model"": ""SUV"", ""Engine"": { ""Horsepower"": 250, ""Type"": ""V8"" } } ] }"; Garage garage = JsonSerializer.Deserialize<Garage>(json); Console.WriteLine($"Car 1 Model: {garage.Cars[0].Model}, Engine Type: {garage.Cars[0].Engine.Type}"); 
  6. Deserialize Nested JSON with Custom Naming Conventions in C#

    • Description: This snippet demonstrates how to handle custom naming conventions when deserializing nested JSON into C#.
    • Code:
      using System.Text.Json; using System.Text.Json.Serialization; public class Product { [JsonPropertyName("product_name")] public string Name { get; set; } [JsonPropertyName("product_price")] public double Price { get; set; } } string json = @"{ ""product_name"": ""Smartphone"", ""product_price"": 699.99 }"; Product product = JsonSerializer.Deserialize<Product>(json); Console.WriteLine($"Product Name: {product.Name}, Price: {product.Price}"); 
  7. Deserialize JSON with Nested Dictionaries into C#

    • Description: This snippet demonstrates how to deserialize JSON containing nested dictionaries into C# classes.
    • Code:
      using System.Text.Json; public class Data { public Dictionary<string, string> Info { get; set; } // Nested dictionary } string json = @"{ ""Info"": { ""key1"": ""value1"", ""key2"": ""value2"" } }"; Data data = JsonSerializer.Deserialize<Data>(json); Console.WriteLine($"Key1: {data.Info["key1"]}, Key2: {data.Info["key2"]}"); 
  8. Deserialize Nested JSON with JsonConverter in C#

    • Description: This snippet shows how to use a custom JsonConverter to deserialize complex nested JSON into C# classes.
    • Code:
      using System; using System.Text.Json; using System.Text.Json.Serialization; public class TemperatureConverter : JsonConverter<double> { public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetDouble(); } public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } } public class Weather { [JsonConverter(typeof(TemperatureConverter))] public double Temperature { get; set; } // Custom deserialization } string json = @"{ ""Temperature"": 72.5 }"; Weather weather = JsonSerializer.Deserialize<Weather>(json); Console.WriteLine($"Temperature: {weather.Temperature} degrees"); 
  9. Deserialize JSON with Nested Enums into C#

    • Description: This code snippet demonstrates how to handle nested JSON that contains enums during deserialization into C#.
    • Code:
      using System.Text.Json; public enum Status { Pending, Completed, Cancelled } public class Task { public string TaskName { get; set; } public Status TaskStatus { get; set; } // Nested enum } string json = @"{ ""TaskName"": ""Code Review"", ""TaskStatus"": ""Completed"" }"; Task task = JsonSerializer.Deserialize<Task>(json); Console.WriteLine($"Task: {task.TaskName}, Status: {task.TaskStatus}"); 
  10. Deserialize JSON with Nested Lists of Objects into C#

    • Description: This snippet demonstrates how to handle nested JSON with lists of objects during deserialization into C#.
    • Code:
      using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Group { public string GroupName { get; set; } public List<Person> Members { get; set; } // Nested list } string json = @"{ ""GroupName"": ""Developers"", ""Members"": [ { ""Name"": ""Alice"", ""Age"": 30 }, { ""Name"": ""Bob"", ""Age"": 35 } ] }"; Group group = JsonSerializer.Deserialize<Group>(json); Console.WriteLine($"Group Name: {group.GroupName}, First Member: {group.Members[0].Name}"); 

More Tags

database-dump pdftk ecmascript-5 xslt-grouping expo digital-signature dialog jenkins-workflow blank-line libsndfile

More Programming Questions

More Transportation Calculators

More Biochemistry Calculators

More Tax and Salary Calculators

More Geometry Calculators