dynamically deserialize json into any object passed in. c#

天大地大妈咪最大 提交于 2019-12-06 14:13:33

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.

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 );

You can ignore the generic method and use dynamic:

var myObj = (dynamic)JsonConvert.DeserializeObject(result);

However, if the objects aren't of the same type you'll have a hard time distinguishing between the types and probably hit runtime errors.

This is the best way to populate an object's fields given JSON data.

This code belongs in the object itself as a method.

public void PopulateFields(string jsonData)
{
    var jsonGraph = JObject.Parse(jsonData);
    foreach (var prop in this.GetType().GetProperties())
    {
        try
        {
            prop.SetValue(this, fields[prop.Name].ToObject(prop.PropertyType), null);
        }
        catch (Exception e)
        {
            // deal with the fact that the given
            // json does not contain that property
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!