c# Json反序列化表达式
本文关键字:表达式 反序列化 Json | 更新日期: 2023-09-27 18:02:51
也许有人知道解决办法。我不能反序列化表达式。
客户端:
var expresion= (Expression<Func<Company, bool>>)(model => model.Id ==id);
var respond = new JObject();
respond .Add("Expression", JToken.FromObject(expresion));
服务器端:
JsonSerializer serializer = new JsonSerializer();
serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
T p = (T)serializer.Deserialize(new JTokenReader(jObject), typeof(T));
:
{"Unable to find a constructor to use for type System.Linq.Expressions.Expression`1[System.Func`2[HostStorageModels.Company,System.Boolean]]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Expression.Type'."}
我认为它显式地告诉您没有构造函数来构建表达式。如果您在MSDN文档中检查Expression Constructor(),您将看到它是受保护的。您可以尝试以其他可序列化的格式发送表达式,并在另一端接收到它时重新构建它。
https://github.com/6bee/Remote.Linq
var query = (Expression<Func<Person, bool>>)(model => model.FirstName == "test2");
var remoteExpression = query.ToRemoteLinqExpression();
var request = new Request<Person>
{
Items = new List<Person>()
{
new Person() { FirstName = "test", Id = 1 },
new Person() { FirstName = "test2", Id = 2 }
},
Expression = remoteExpression
};
var serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
string jsonString = JsonConvert.SerializeObject(request, serializerSettings);
var result = JsonConvert.DeserializeObject<Request<Person>>(jsonString, serializerSettings);
var expresion = result.Expression.ToLinqExpression<Person, bool>();
var filtered = request.Items.Where(expresion.Compile()).ToList();