动态将json反序列化为传入的任何对象.c# [英] dynamically deserialize json into any object passed in. c#

查看:378
本文介绍了动态将json反序列化为传入的任何对象.c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将json反序列化为c#中的对象.我想要做的是传递任何对象以获取其类型,然后使用JSON.Net库将json反序列化为该特定对象.这是代码行.

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

最后一行抛出

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

我如何在<>中获取数据类型而又不抱怨c#.要使此代码正常工作,我该怎么做?而我缺少什么知识?

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?

推荐答案

JsonConvert.DeserializeObject<T>需要编译时类型.您不能像您想做的那样在运行时将其传递给类型(与声明List<T>没什么不同).您应该反序列化为通用的json对象JObject(或 dynamic ),或者应该创建对象的实例并用json填充它.

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.

您可以使用静态方法PopulateObject(当然,如果对象的属性匹配要反序列化的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 );

这篇关于动态将json反序列化为传入的任何对象.c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆