using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
public int Id { get; set; }
public string Name { get; set; }
public static void Test()
var jsonString = GetJson();
Console.WriteLine("Input JSON: ");
Console.WriteLine(jsonString);
TestJsonDocument(jsonString);
TestSerializer(jsonString);
static void TestReader(string jsonString)
var comments = GetComments(jsonString);
Console.WriteLine("Comments found in JSON using Utf8JsonReader:");
Console.WriteLine(string.Concat(comments.Select(s => " " + s + "\n")));
static void TestJsonDocument(string jsonString)
var options = new JsonDocumentOptions
CommentHandling = JsonCommentHandling.Skip,
using var doc = JsonDocument.Parse(jsonString, options);
Console.WriteLine("Reserialized {0}:", doc);
Console.WriteLine(doc.ToJson());
static void TestSerializer(string jsonString)
var options = new JsonSerializerOptions
ReadCommentHandling = JsonCommentHandling.Skip
var person = JsonSerializer.Deserialize<Person>(jsonString, options);
var json2 = JsonSerializer.Serialize(person);
Console.WriteLine("Re-serialized {0}:", person);
Console.WriteLine(json2);
static List<string> GetComments(string jsonString)
var options = new JsonReaderOptions
CommentHandling = JsonCommentHandling.Allow
var list = new List<string>();
var reader = new Utf8JsonReader(new ReadOnlySpan<byte>(Encoding.UTF8.GetBytes(jsonString)), options);
if (reader.TokenType == JsonTokenType.Comment)
list.Add(reader.GetComment());
""Id"" : 1 /* Person's ID */,
""Name"" : ""Foo"" // Person's name
public static partial class JsonExtensions
public static string ToJson(this JsonDocument doc)
return doc.RootElement.ToJson();
public static string ToJson(this JsonElement element)
using var ms = new MemoryStream();
using (var writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
return Encoding.UTF8.GetString(ms.ToArray());
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("System.Text.Json version: " + typeof(JsonDocument).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];