🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 5 Min Lesezeit
0

Serializing and Deserializing Records in C#

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Records in C# provide a concise and immutable way to define data structures. Their built-in features make serialization and deserialization with System.Text.Json effortless. Whether you need a simple JSON representation or advanced customization, records offer great flexibility. This article dives into these features with multiple examples, covering common and advanced scenarios.









Serializing a Record to JSON



Serializing a record to JSON is straightforward. Let’s create a Student record and convert it into a JSON string:




CODE
using System.Text.Json;

public record Student(string Name, int Age);

class Program
{
static void Main()
{
var student = new Student("Alice", 21);

// Serialize the record to JSON
string json = JsonSerializer.Serialize(student);

Console.WriteLine(json);
}
}









Output:






CODE
{"Name":"Alice","Age":21}






Here, the JsonSerializer automatically maps the record properties to JSON key-value pairs.









Formatting JSON Output



To make the JSON output more readable, use the WriteIndented option:




CODE
var options = new JsonSerializerOptions { WriteIndented = true };
string indentedJson = JsonSerializer.Serialize(student, options);
Console.WriteLine(indentedJson);









Output:






CODE
{
"Name": "Alice",
"Age": 21
}












Deserializing JSON into a Record



The Deserialize method maps JSON back into a record instance. Let’s reverse the process:




CODE
string jsonInput = "{\"Name\":\"Alice\",\"Age\":21}";

// Deserialize JSON to a Student record
var deserializedStudent = JsonSerializer.Deserialize<Student>(jsonInput);

Console.WriteLine(deserializedStudent);









Output:






CODE
Student { Name = Alice, Age = 21 }












Customizing JSON Property Names



Sometimes, you need to rename JSON properties for external APIs or readability. Use [JsonPropertyName] to customize property names.






Example: Renaming Properties






CODE
using System.Text.Json.Serialization;

public record Product(
[property: JsonPropertyName("product_name")] string Name,
[property: JsonPropertyName("product_cost")] decimal Price
);

class Program
{
static void Main()
{
var product = new Product("Tablet", 600.00m);

// Serialize with custom JSON property names
string json = JsonSerializer.Serialize(product);
Console.WriteLine(json);

// Deserialize JSON back to Product
string jsonInput = "{\"product_name\":\"Tablet\",\"product_cost\":600.0}";
var deserializedProduct = JsonSerializer.Deserialize<Product>(jsonInput);
Console.WriteLine(deserializedProduct);
}
}









Output:



Serialized JSON:




CODE
{"product_name":"Tablet","product_cost":600.0}






Deserialized Record:




CODE
Product { Name = Tablet, Price = 600.0 }












Ignoring Properties During Serialization



You can exclude specific properties using the [JsonIgnore] attribute. Let’s extend the Product record with a field we want to ignore.






Example: Ignoring a Property






CODE
public record Product(
string Name,
decimal Price,
[property: JsonIgnore] string InternalCode
);

class Program
{
static void Main()
{
var product = new Product("Phone", 1200.00m, "SECRET123");

// Serialize to JSON
string json = JsonSerializer.Serialize(product);
Console.WriteLine(json);

// Deserialize JSON back to Product
string jsonInput = "{\"Name\":\"Phone\",\"Price\":1200.0}";
var deserializedProduct = JsonSerializer.Deserialize<Product>(jsonInput);
Console.WriteLine(deserializedProduct);
}
}









Output:



Serialized JSON:




CODE
{"Name":"Phone","Price":1200.0}






Deserialized Record:




CODE
Product { Name = Phone, Price = 1200.0, InternalCode = }






The InternalCode property is ignored during serialization but retains its default value when deserialized.









Advanced Scenarios






Ignoring Null Values



If you want to exclude null properties from JSON, use the DefaultIgnoreCondition option.




CODE
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

var product = new Product("Tablet", 500.00m, null);
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);









Output:






CODE
{"Name":"Tablet","Price":500.0}












Nested Records and Serialization



Records can be nested, and JSON serialization handles this seamlessly.




CODE
public record Address(string Street, string City);
public record Customer(string Name, Address Address);

class Program
{
static void Main()
{
var customer = new Customer("John", new Address("123 Main St", "Springfield"));

// Serialize to JSON
string json = JsonSerializer.Serialize(customer, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

// Deserialize JSON back to Customer
string jsonInput = "{\"Name\":\"John\",\"Address\":{\"Street\":\"123 Main St\",\"City\":\"Springfield\"}}";
var deserializedCustomer = JsonSerializer.Deserialize<Customer>(jsonInput);
Console.WriteLine(deserializedCustomer);
}
}









Output:



Serialized JSON:




CODE
{
"Name": "John",
"Address": {
"Street": "123 Main St",
"City": "Springfield"
}
}






Deserialized Record:




CODE
Customer { Name = John, Address = Address { Street = 123 Main St, City = Springfield } }












Handling Arrays in Records



Records with array or collection properties are fully supported. Let’s serialize a record with a list of orders:




CODE
public record Order(int Id, string Product, int Quantity);
public record OrderBatch(string Customer, List<Order> Orders);

class Program
{
static void Main()
{
var batch = new OrderBatch(
"Alice",
new List<Order>
{
new Order(1, "Phone", 2),
new Order(2, "Tablet", 1)
}
);

// Serialize the order batch to JSON
string json = JsonSerializer.Serialize(batch, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

// Deserialize JSON back to OrderBatch
string jsonInput = "{\"Customer\":\"Alice\",\"Orders\":[{\"Id\":1,\"Product\":\"Phone\",\"Quantity\":2},{\"Id\":2,\"Product\":\"Tablet\",\"Quantity\":1}]}";
var deserializedBatch = JsonSerializer.Deserialize<OrderBatch>(jsonInput);
Console.WriteLine(deserializedBatch);
}
}









Output:



Serialized JSON:




CODE
{
"Customer": "Alice",
"Orders": [
{
"Id": 1,
"Product": "Phone",
"Quantity": 2
},
{
"Id": 2,
"Product": "Tablet",
"Quantity": 1
}
]
}






Deserialized Record:




CODE
OrderBatch { Customer = Alice, Orders = [Order { Id = 1, Product = Phone, Quantity = 2 }, Order { Id = 2, Product = Tablet, Quantity = 1 }] }












Assignments






Easy Level




  1. Serialize a Person record with Name and Age into JSON and print it.

  2. Deserialize {"Name":"Jane","Age":30} into a Person record.









Medium Level




  1. Add a [JsonPropertyName] attribute to the Person record to rename Name to full_name and Age to person_age.

  2. Add a PhoneNumber property to Person and use [JsonIgnore] to exclude it from serialization.









Difficult Level





  1. Create an Invoice record with:





    • InvoiceNumber (string), Amount (decimal), and DueDate (DateTime).

    • Use [JsonPropertyName] to rename all properties for JSON output.

    • Exclude DueDate from serialization using [JsonIgnore].




  2. Create a Company record with:





    • Name (string) and Employees (List).

    • Serialize and deserialize the Company record with nested Person records.











Conclusion



Serializing and deserializing records in C# is straightforward, and with attributes like [JsonPropertyName] and [JsonIgnore], you can fine-tune how records interact with JSON. By mastering these features, you can create flexible, JSON-ready data models for real-world applications.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Serializing and Deserializing Records in C#

Thematisch verwandte Begriffe: Serializing, Deserializing, Records · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...