简体   繁体   English

使用Reflection将JSON反序列化为不同的类

[英]Deserialize JSON into different classes using Reflection

I am working on windows phone 8.1 application. 我正在使用Windows Phone 8.1应用程序。 I am working with REST API and the the api return me JSON data. 我正在使用REST API,而api则返回JSON数据。 I want to create a method such that each time I call the API, I just send the type of class on which it is to be deserialized as a parameter and I get the deserialized data into an object of that model. 我想创建一个方法,每次我调用API时,我只是将要反序列化的类的类型作为参数发送,然后我将反序列化的数据放入该模型的对象中。 My current code looks like this: 我当前的代码如下所示:

public static async Task GetAPIData(Type referanceModel, string serviceUrl)
    {
        HttpClient client = new HttpClient();
        var responce = await client.GetAsync(new Uri(serviceUrl));
        JArray arr = JArray.Parse(await response.Content.ReadAsStringAsync());

        foreach (JObject obj in arr.Children<JObject>())
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;

            var rcvdData = JsonConvert.DeserializeObject<referanceModel>(obj.ToString(), settings);


            //var method = typeof(JsonConvert).GetTypeInfo().GetDeclaredMethods("DeserializeObject").ToList()[5].MakeGenericMethod(ReferanceModel);


            //var rcvd = method.Invoke(null, new object[] { obj.ToString(), settings });
        }

    }

The above code shows me the error that referanceModel is a variable. 上面的代码显示了referanceModel是一个变量的错误。 I tried the commented code also but it doesn't work too. 我也尝试了注释代码,但它也不起作用。

The two classes are: AllvehData and AllDevicesData. 这两个类是:AllvehData和AllDevicesData。 Both of these classes are inside a singleton class called ThisUserClass with the instance of ThisUser 这两个类都在一个名为ThisUserClass的单​​例类中,其中包含ThisUser的实例

public class AllVehData
{
    public string Colour { get; set; }
    public string Make { get; set; }
    public string model { get; set; }
    public string Year { get; set; }


 }


 public class AllDevicesData
{
    bool has_tracking_device { get; set; }
    int drive_type_name_string_id { get; set; }
    public int vehicle_status { get; set; }
    public int cargo_capacity { get; set; }
    public int fuel_capacity { get; set; }
}

I searched a lot on the topic and found this but failed to understand. 我在这个主题上搜索了很多,发现了这个但却没能理解。 I need help. 我需要帮助。

In this case you don't need the generic overload JsonConvert.DeserializeObject<>(string, JsonSerializerSettings) . 在这种情况下,您不需要泛型重载JsonConvert.DeserializeObject<>(string, JsonSerializerSettings) Instead use the JsonConvert.DeserializeObject(string, Type, JsonSerializerSettings) overload and do: 而是使用JsonConvert.DeserializeObject(string, Type, JsonSerializerSettings)重载并执行:

var rcvdData = JsonConvert.DeserializeObject(obj.ToString(), referanceModel, settings);

When you use generics - either class or method - you MUST pass an actual type in the place of a generic parameter as opposed of a variable of type Type . 当您使用泛型(类或方法)时,您必须在泛型参数的位置传递实际类型,而不是类型为Type的变量。 This is the reason you get compile time error. 这是您遇到编译时错误的原因。 Eg in order to initialize a list of strings you cannot do: 例如,为了初始化一个你不能做的字符串列表:

var theStringVar = string.Empty;
var myList1 = new List<theStringVar>(); // Here we get the compile time error.

// OR

var theTypeVar = typeof(string);
var myList2 = new List<theTypeVar>(); // That won't work either.

Instead you need to specify the string type explicitly: 相反,您需要明确指定string类型:

var myList3 = new List<string>(); // This works just fine.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM