且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态将json反序列化为传入的任何对象.c#

更新时间:2023-02-17 19:37:22

JsonConvert.DeserializeObject<T>需要编译时类型.您不能像您想做的那样在运行时将其传递给类型(与声明List<T>没什么不同).您应该反序列化为通用的json对象JObject(或 dynamic ),或者应该创建对象的实例并用json填充它.

JsonConvert.DeserializeObject<T> needs a compile-time type. You can't pass it a type in run time as you want to do in question (nothing different than declaring a List<T>). You should either deserialize to a generic json object JObject (or to dynamic) or you should create an instance of an object and fill it with json.

您可以使用静态方法PopulateObject(当然,如果对象的属性匹配要反序列化的json).

You can use the static method PopulateObject (of course if your object's properties match the json you want to deserialize).

JsonConvert.PopulateObject(result, someObject1 );