问题
Usually we deserialize using JSON.NET by this code
JsonConvert.DeserializeObject<CLASS TYPE> (text, settings);
Imagine, that we have such JSON request:
{
"command" : "register_user",
"params" : {
"@c" : "register_params",
"name" : "sdfsd",
"email" : "sdfsd@ddkdk",
"password" : "JDFffJJJd"
}
}
How could we automatically detect that we need deserialize "name", "email" and "password" fields into one register_params object using JSON.NET?
回答1:
Using the TypeName value "$type".
I've written two methods to do as such:
//T can be an interface or a derived type
public static T DeserializeObject<T>(string json) where T : class
//Uses "$type" to determine the object
public static object DeserializeObject(string json)
source: https://gist.github.com/ricjac/b84a1d550cfe469f3945
来源:https://stackoverflow.com/questions/11313793/json-net-deserialize-json-into-object-which-class-type-is-in-inner-field