|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Reflection; |
| 4 | + |
| 5 | +using Newtonsoft.Json; |
| 6 | +using Newtonsoft.Json.Serialization; |
| 7 | + |
| 8 | +namespace Umbraco.Cms.Integrations.Commerce.Shopify.Resolvers |
| 9 | +{ |
| 10 | + public class JsonPropertyRenameContractResolver : DefaultContractResolver |
| 11 | + { |
| 12 | + private readonly Dictionary<Type, Dictionary<string, string>> _renames; |
| 13 | + |
| 14 | + public JsonPropertyRenameContractResolver() |
| 15 | + { |
| 16 | + _renames = new Dictionary<Type, Dictionary<string, string>>(); |
| 17 | + } |
| 18 | + |
| 19 | + public void RenameProperty(Type type, string propertyName, string newJsonPropertyName) |
| 20 | + { |
| 21 | + if (!_renames.ContainsKey(type)) |
| 22 | + _renames[type] = new Dictionary<string, string>(); |
| 23 | + |
| 24 | + _renames[type][propertyName] = newJsonPropertyName; |
| 25 | + } |
| 26 | + |
| 27 | + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) |
| 28 | + { |
| 29 | + var property = base.CreateProperty(member, memberSerialization); |
| 30 | + |
| 31 | + if (IsRenamed(property.DeclaringType, property.PropertyName, out var newJsonPropertyName)) |
| 32 | + property.PropertyName = newJsonPropertyName; |
| 33 | + |
| 34 | + return property; |
| 35 | + } |
| 36 | + |
| 37 | + private bool IsRenamed(Type type, string jsonPropertyName, out string newJsonPropertyName) |
| 38 | + { |
| 39 | + if (!_renames.TryGetValue(type, out var renames) || !renames.TryGetValue(jsonPropertyName, out newJsonPropertyName)) |
| 40 | + { |
| 41 | + newJsonPropertyName = null; |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + return true; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments