14

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

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

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

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

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

4

1 回答 1

16

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.

于 2012-10-10T20:45:22.360 回答