使用newtonsoft,如何在不知道类型直到运行时反序列化?

时间:2022-08-04 10:00:56

so the followwing works just fine, giving me a Team object from the string json:

所以followwing工作得很好,从字符串json给我一个Team对象:

var found = JsonConvert.DeserializeObject<Team>(json);

but what if I won't know the type until runtime? Say I've got the string json as above, but I also have another string with the type name? for example, this isn't working:

但是如果直到运行时我才知道类型怎么办?假设我上面有字符串json,但我还有另一个字符串类型名称?例如,这不起作用:

var found = JsonConvert.DeserializeObject(json, Type.GetType("Team"));

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type ...

无法将“Newtonsoft.Json.Linq.JArray”类型的对象强制转换为...

1 个解决方案

#1


7  

This worked for me:

这对我有用:

var type = Type.GetType("My.Namespace.Class");
var myObj = JsonConvert.DeserializeObject(item, type);

The trick is to make sure that type is not null by providing the correct class name. If it is, the Deserialization can still work, but the output won't be the type you are wanting. See MSDN for more info on GetType.

诀窍是通过提供正确的类名来确保类型不为null。如果是,反序列化仍然可以工作,但输出将不是您想要的类型。有关GetType的更多信息,请参阅MSDN。

#1


7  

This worked for me:

这对我有用:

var type = Type.GetType("My.Namespace.Class");
var myObj = JsonConvert.DeserializeObject(item, type);

The trick is to make sure that type is not null by providing the correct class name. If it is, the Deserialization can still work, but the output won't be the type you are wanting. See MSDN for more info on GetType.

诀窍是通过提供正确的类名来确保类型不为null。如果是,反序列化仍然可以工作,但输出将不是您想要的类型。有关GetType的更多信息,请参阅MSDN。