Serialize expression tree

前端 未结 3 975
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 04:14

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

I need to be able to serialize Predicate with type

Predicate

        
3条回答
  •  [愿得一人]
    2021-02-01 05:04

    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 obj)
        {
            return JsonConvert.SerializeObject(obj, _settings);
        }
    
        public T Deserialize(string json)
        {
            return JsonConvert.DeserializeObject(json, _settings);
        }
    }
    

    Works like a charm!

提交回复
热议问题