Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

c# - Deserialize JSON referencing a type from string name in a type parameter

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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<Customers>(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.

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.


Trying to access a property like this:

var name = myObject["Name"];

is easier than reflection, but it's ultimately the same thing as

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...