← Back to C# Course | Chapter 14: File I/O & Streams | Lesson 6 of 6

Serialization की Basics

Serialization किसी object को boxed puzzle की तरह flat पैक करना है ताकि इसे save या भेजा जा सके, और फिर बाद में फिर से बनाया जा सके। यह आपके data को text या bytes में बदल देता है जो यात्रा कर सकें।

In this page:

  1. Serialization Basics
Syntax
csharp
using System.Text.Json;

string json = JsonSerializer.Serialize(objectValue);
ClassName obj = JsonSerializer.Deserialize<ClassName>(json);

Serialization Basics

Serialization किसी object को एक storable या transmittable format में convert करता है, जैसे JSON, और deserialization process को उल्टा करता है।

System.Text.Json modern .NET में इसके लिए JsonSerializer.Serialize और JsonSerializer.Deserialize प्रदान करता है। structured data को किसी file में save करने या network पर भेजने का यह standard तरीका है।

Note: Public properties (fields नहीं) वे हैं जिन्हें System.Text.Json default रूप से serialize करता है।

उदाहरण: Serialization Basics

markup
using System;
using System.Text.Json;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person { Name = "Nina", Age = 27 };

        string json = JsonSerializer.Serialize(p);
        Console.WriteLine(json);

        Person restored = JsonSerializer.Deserialize<Person>(json);
        Console.WriteLine($"{restored.Name}, {restored.Age}");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. class पर साधारण public fields declare करना और उन्हें JSON में उम्मीद करना, जबकि System.Text.Json default रूप से सिर्फ public properties (एक getter के साथ) serialize करता है।
  2. ऐसी JSON deserialize करना जिसके property names case में अलग हों, जैसे Name के बजाय name, और खाली values पाना क्योंकि matching case-sensitive है जब तक PropertyNameCaseInsensitive सेट न हो।
  3. बिना null check के JsonSerializer.Deserialize<Person>(json) के result का उपयोग करना, जबकि यह null return कर सकता है।
चैप्टर सारांश
  • File.ReadAllText और StreamReader तथा StreamWriter files पढ़ते और लिखते हैं।
  • Directory, Path, और FileInfo folders, paths, और file details के साथ काम करते हैं।
  • Serialization basics objects को stored data में बदलते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.