using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Bson;
public static partial class BsonExtensions
public static void SerializeToFile<T>(T obj, string path, JsonSerializerSettings settings = null)
using (var stream = new FileStream(path, FileMode.Create))
using (var writer = new BsonWriter(stream))
JsonSerializer.CreateDefault(settings).Serialize(writer, obj);
public static T DeserializeFromFile<T>(string path, JsonSerializerSettings settings = null)
using (var stream = new FileStream(path, FileMode.Open))
using (var reader = new BsonReader(stream))
var serializer = JsonSerializer.CreateDefault(settings);
if (serializer.ContractResolver.ResolveContract(typeof(T)) is JsonArrayContract)
reader.ReadRootValueAsArray = true;
return serializer.Deserialize<T>(reader);
public RootObject MySelf { get { return this; } }
public static void Test()
var path = "Question58635698.bson";
public static void Test(string path)
var objectToSave = new [] { new RootObject() };
BsonExtensions.SerializeToFile(objectToSave, path,
new JsonSerializerSettings
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
var objectToRetrieve = BsonExtensions.DeserializeFromFile<RootObject []>(path,
new JsonSerializerSettings
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
Console.WriteLine("{0} round-tripped successfully.", objectToRetrieve.GetType().FullName);
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).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];