Created
March 19, 2017 15:57
-
-
Save Arakade/de0caff816e2d7e5ebaabcffa41f9a24 to your computer and use it in GitHub Desktop.
Save something with JsonDotNet (Json.Net) using Serializable attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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