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 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);
  }
}

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