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);
}
}
}
}