dynamically deserialize json into any object passed in. c#

不想你离开。 提交于 2019-12-07 19:44:47

问题


I'm trying to do is deserialize json into an object in c#. What I want to be able to do is pass any object get it's type and deserialize the json into that particular object using the JSON.Net library. Here are the lines of code.

 Object someObject1 = someObject;
 string result = await content.ReadAsStringAsync();
 return JsonConvert.DeserializeObject<someObject1.GetType()>(result);

The last line throws an exception of

 operator '<' cannot be applied to operands of type 'method group'

How do I get the data type in the <> without c# complaining. What do I have to do to make this code work? And what knowledge am I missing?


回答1:


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



回答2:


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.




回答3:


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
        }
}


来源:https://stackoverflow.com/questions/25672338/dynamically-deserialize-json-into-any-object-passed-in-c-sharp

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