From 62f9b86c1d7fff7fa52344a038be2d3c1806e041 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Sun, 1 Nov 2020 00:48:44 +0100 Subject: [PATCH] added a json extension to mlem.data for easy json property modification --- MLEM.Data/Json/JsonExtensions.cs | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 MLEM.Data/Json/JsonExtensions.cs diff --git a/MLEM.Data/Json/JsonExtensions.cs b/MLEM.Data/Json/JsonExtensions.cs new file mode 100644 index 0000000..c02f975 --- /dev/null +++ b/MLEM.Data/Json/JsonExtensions.cs @@ -0,0 +1,40 @@ +using System; +using System.Reflection; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace MLEM.Data.Json { + /// + /// A set of extensions for dealing with the Newtonsoft.JSON . + /// + public static class JsonExtensions { + + /// + /// Changes the to a contract resolver that queries each newly created and allows modifying it easily. + /// This removes the need to create a new contract resolver class for modifying created json properties. + /// + /// The serializer to which to add the property modifier + /// A function that takes in the json property and allows returning a modified property (or the same one) + /// + public static JsonSerializer SetPropertyModifier(this JsonSerializer serializer, Func propertyModifier) { + serializer.ContractResolver = new PropertyModifierResolver(propertyModifier); + return serializer; + } + + private class PropertyModifierResolver : DefaultContractResolver { + + private readonly Func propertyModifier; + + public PropertyModifierResolver(Func propertyModifier) { + this.propertyModifier = propertyModifier; + } + + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { + var property = base.CreateProperty(member, memberSerialization); + return this.propertyModifier(property); + } + + } + + } +} \ No newline at end of file