Search code examples
c#serializationlambdaexpression-trees

Serialize expression tree


I'm doing a distributed system in c# and have encountered a barrier.

I need to be able to serialize Predicate with type

Predicate<ICollection<IEntity>> p = (entities => entities.OfType<Person>().Count() <= 3);

I belive this is not possible in .net so my question is if there exists any frameworks that can do the trick.

I've already tried a couple of frameworks, but keep running into the problem that their are not able to serialize predicates that takes a collection or list

Hope anyone knows a solution. Have been stuck with this problem for a couple of weeks now...


Solution

  • My Solution:

    After putting the issue to rest for a long time I finally managed to solve my problem using json.net and Aq.ExpressionJsonSerializer (https://github.com/aquilae/expression-json-serializer)

    public class JsonNetAdapter : IOconSerializer
    {
        private readonly JsonSerializerSettings _settings;
    
        public JsonNetAdapter(JsonSerializerSettings settings = null)
        {
            var defaultSettings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects};
            defaultSettings.Converters.Add(new ExpressionJsonConverter(Assembly.GetAssembly(typeof(IOconSituation))));
            _settings = settings ?? defaultSettings;
        }
    
        public string Serialize<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj, _settings);
        }
    
        public T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json, _settings);
        }
    }
    

    Works like a charm!