commodore73

Add JsonConverters for Contentstack Modular Block Fields

Jul 23rd, 2020
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. namespace Root.Core.Models.Configuration
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Reflection;
  6.     using System.Diagnostics;
  7.  
  8.     using Newtonsoft.Json;
  9.  
  10.     using Deliverystack.Core.Attributes;
  11.     using Deliverystack.Core.Configuration;
  12.  
  13.     using Root.Core.Models.Fields;
  14.  
  15.     public class SerializationConfigurator : IConfigureSerialization
  16.     {
  17.         private List<JsonConverter> _jsonConverters = null;
  18.  
  19.         public void ConfigureSerialization(JsonSerializerSettings settings)
  20.         {
  21.             if (_jsonConverters == null)
  22.             {
  23.                 _jsonConverters = new List<JsonConverter>();
  24.  
  25.                 foreach (Type type in AutoLoadJsonConverter.GetTypesWithAttribute(typeof(AutoLoadJsonConverter)))
  26.                 {
  27.                     if (AutoLoadJsonConverter.IsEnabledForType(type))
  28.                     {
  29.                         _jsonConverters.Add((JsonConverter)Activator.CreateInstance(type));
  30.                     }
  31.                 }
  32.  
  33.                 foreach (Type blockType in ModularBlockBase.Implementations)
  34.                 {
  35.                     //TODO: since they all inherit, this doesn't require reflection - just create them as the base class and call the method?
  36.  
  37.                     MethodInfo methodInfo = blockType.GetRuntimeMethod("GetJsonConverter", new Type[0]);
  38.                     Trace.Assert(methodInfo != null, "GetJsonConverter() not found in " + blockType);
  39.                     object obj = Activator.CreateInstance(blockType);
  40.                     JsonConverter jsonConverter = methodInfo.Invoke(obj, new object[0]) as JsonConverter;
  41.                     Trace.Assert(jsonConverter != null, "No JsonConverter for " + blockType);
  42.                     _jsonConverters.Add(jsonConverter);
  43.                 }
  44.             }
  45.  
  46.             foreach (JsonConverter jsonConverter in _jsonConverters)
  47.             {
  48.                 settings.Converters.Add(jsonConverter);
  49.             }
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment