Skip to content

Instantly share code, notes, and snippets.

@Arakade
Created March 19, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arakade/de0caff816e2d7e5ebaabcffa41f9a24 to your computer and use it in GitHub Desktop.
Save Arakade/de0caff816e2d7e5ebaabcffa41f9a24 to your computer and use it in GitHub Desktop.
Save something with JsonDotNet (Json.Net) using Serializable attribute
static void save(string filePath) {
// ...
using (TextWriter writer = File.CreateText(filePath)) {var serializer = getSerializer(errors);
var errors = new List<string>();
var serializer = getSerializer(errors);
serializer.Serialize(writer, snapshot);
logErrors(errors);
}
// ...
}
private static JsonSerializer getSerializer(List<string> errors) {
JsonSerializer serializer = new JsonSerializer();
// This next line forces Serializable use.
serializer.ContractResolver = new MyContractResolver();
serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
serializer.MissingMemberHandling = MissingMemberHandling.Error;
serializer.Error += (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) => {
errors.Add(string.Format("'{1}' from '{0}'", sender, args.ErrorContext.Error.Message));
};
return serializer;
}
private sealed class MyContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver {
public MyContractResolver() : base() {
IgnoreSerializableAttribute = false; // Use SerializableAttribute to determine what to serialize!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment