JSON.NET - deserialize JSON into object, which class type is in inner field

落爺英雄遲暮 提交于 2019-12-11 17:31:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!