从类型参数的字符串名称中反序列化引用类型的JSON [英] Deserialize JSON referencing a type from string name in a type parameter

查看:69
本文介绍了从类型参数的字符串名称中反序列化引用类型的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var custsType = Type.GetType("Customers");          
var customers = Json.Deserialize<custsType>(data);

这显然失败了.如何通过字符串名称引用该类,以便可以在运行时提供它?

This obviously fails. How do I reference the class by string name so I can supply it at runtime?

此外,我需要能够访问实际的强类型对象,而不是其字符串表示形式.

Also, I need to be able to have access to the actual strong typed object, not its string representation..

推荐答案

var custsType = Type.GetType("Customers");          
var customers = JsonConvert.DeserializeObject(data, custsType);

问题是,如果不确定对象的类型,您将很难使用它.大概类型名称是一个参数,否则您将刚刚完成

The problem is that you're going to have difficulty using the object if its type is uncertain. Presumably the type name is a parameter, otherwise you would have just done

var customers = JsonConvert.DeserializeObject<Customers>(data);

这表明在编译时您不知道期望该类型返回什么类型.这样做的问题是,如果您在编译时不知道该类型,则不清楚一旦获得该对象就可以对其进行处理.

It suggests that at compile time you don't know what type you expect this to return. The problem with that is that if you don't know the type at compile time, it's unclear what you can do with the object once you get it.

如果要访问对象的任何属性,则必须预先确定对象的类型.否则,您将不会期望反序列化的对象具有该属性.

If you intend to access any properties of the object then you must have some assumption up front about what the type of the object would be. Otherwise you wouldn't expect the deserialized object to have that property.

面临的挑战不是如何解决问题,而是如何重新考虑该方法,这样一来您就不会遇到问题.

The challenge isn't how to solve the problem, but how to reconsider the approach so that you don't have the problem in the first place.

理想情况下,您想知道在编译时期望的类型,再次看起来像这样:

Ideally you want to know the type that you expect at compile time, which would look like this again:

var customers = JsonConvert.DeserializeObject(data, custsType);

然后,如果无法将数据反序列化为期望的类型,则会引发异常,因为调用方必须传递正确的类型.

Then if the data can't be deserialized to the expected type, it throws an exception because the caller must pass the correct type.

如果您发现自己处在以下位置:a)您不知道类型是什么,或b)您必须使用反射来查找属性,则说明出现了问题,最好备份直到可以解决这个问题.

If you find yourself in a spot where a) you don't know what the type is, or b) you have to use reflection to find properties, then something has gone wrong, and it's good to back up until you can fix that.

尝试访问这样的属性:

var name = myObject["Name"];

比反思容易,但最终与

var property = myObject.GetType().GetProperty("Name");
var name = property.GetValue(myObject);

在两种情况下,您都不真正知道是否存在名称"属性.将对象解析为JSON的任何操作都只是在幕后进行反射.

In both cases you don't really know if there will be a "Name" property or not. Whatever parses the object into JSON is just using reflection behind the scenes.

这篇关于从类型参数的字符串名称中反序列化引用类型的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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