0Pricing
C# Academy · Lesson

JSON with System.Text.Json (opt-ins, converters)

C# 6-friendly JSON: use DataContractJsonSerializer with [DataContract]/[DataMember] (opt-in members) and simple naming tweaks akin to converters.

JSON with System.Text.Json (opt-ins, converters) is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

JSON on C# 6: plan

Goal: Serialize/deserialize JSON without external packages.

  • Use DataContractJsonSerializer
  • Opt-in members via DataMember
  • Customize names with Name=
  • Write/read from files safely

Opt-in model

Opt-in model: mark the type with DataContract and only the included members with DataMember. Use Name= to control JSON keys.

using System;
using System.Runtime.Serialization;

[DataContract] // opt-in: only [DataMember] will be serialized
public sealed class User
{
  [DataMember(Name = "id")]
  public int Id { get; set; }

  [DataMember(Name = "name")]
  public string Name { get; set; }

  // Not included: no DataMember
  public string InternalNote { get; set; }
}

public class Program
{
  public static void Main(string[] args)
  {
    User u = new User { Id = 7, Name = "Ada", InternalNote = "hidden" };
    Console.WriteLine("Ready to serialize: " + u.Name);
  }
}

Serialize to JSON

Create a DataContractJsonSerializer, write to a stream, and UTF-8 encode to a string.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

[DataContract]
public sealed class User
{
  [DataMember(Name = "id")]
  public int Id { get; set; }

  [DataMember(Name = "name")]
  public string Name { get; set; }

  public string InternalNote { get; set; }
}

public class Program
{
  public static string ToJson(User u)
  {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
    using (MemoryStream ms = new MemoryStream())
    {
      ser.WriteObject(ms, u);
      return Encoding.UTF8.GetString(ms.ToArray());
    }
  }

  public static void Main(string[] args)
  {
    User u = new User { Id = 1, Name = "Ada", InternalNote = "not saved" };
    string json = ToJson(u);
    Console.WriteLine(json); // {"id":1,"name":"Ada"}
  }
}

Deserialize from JSON

Deserialize by reading from a stream. Only DataMember fields are populated.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

[DataContract]
public sealed class User
{
  [DataMember(Name = "id")]
  public int Id { get; set; }

  [DataMember(Name = "name")]
  public string Name { get; set; }
}

public class Program
{
  public static User FromJson(string json)
  {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
    byte[] bytes = Encoding.UTF8.GetBytes(json);
    using (MemoryStream ms = new MemoryStream(bytes))
    {
      return (User)ser.ReadObject(ms);
    }
  }

  public static void Main(string[] args)
  {
    string json = "{\"id\":42,\"name\":\"Bob\"}";
    User u = FromJson(json);
    Console.WriteLine(u.Id + " - " + u.Name);
  }
}

Save/load JSON files

Persist JSON with FileStream in using blocks. This mirrors real apps: settings, small data, etc.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

[DataContract]
public sealed class Settings
{
  [DataMember(Name = "theme")]
  public string Theme { get; set; }

  [DataMember(Name = "notifications")]
  public bool Notifications { get; set; }
}

public class Program
{
  public static void Save(string path, Settings s)
  {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Settings));
    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
      ser.WriteObject(fs, s);
    }
  }

  public static Settings Load(string path)
  {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Settings));
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
      return (Settings)ser.ReadObject(fs);
    }
  }

  public static void Main(string[] args)
  {
    string path = "settings.json";
    Save(path, new Settings { Theme = "dark", Notifications = true });
    Settings loaded = Load(path);
    Console.WriteLine(loaded.Theme + " / " + loaded.Notifications);
  }
}

Naming & simple conversions

Customize:

  • Use Name= in DataMember to map property names (e.g., user_name)
  • For enums, mark with EnumMember per value
  • For special formats (dates, numbers), convert to a string property (manual mapping) in C# 6

Opt-in rule for JSON

Quick check: With DataContractJsonSerializer, how do you opt in only certain properties for JSON?

Recap

Recap: Use DataContractJsonSerializer on C# 6, opt in members with DataMember, adjust names via Name=, and read/write using safe stream patterns.

Frequently asked questions

Is the “JSON with System.Text.Json (opt-ins, converters)” lesson free?

Yes — the full text of “JSON with System.Text.Json (opt-ins, converters)” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “JSON with System.Text.Json (opt-ins, converters)”?

C# 6-friendly JSON: use DataContractJsonSerializer with [DataContract]/[DataMember] (opt-in members) and simple naming tweaks akin to converters. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “JSON with System.Text.Json (opt-ins, converters)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. System.IO (paths, streams)
  2. JSON with System.Text.Json (opt-ins, converters)
  3. Simple CSV parsing patterns
← Back to C# Academy