Serialize expression tree

cholewa1992 picture cholewa1992 · Apr 23, 2014 · Viewed 10.5k times · Source

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...

Answer

cholewa1992 picture cholewa1992 · Apr 16, 2015

My Solution:

After putting the issue to rest for a long time a 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!