简体   繁体   中英

How to parse a JToken or JObject's Value To A Dynamically Determined Type

I'm hoping that someone could explain how/why this does not work for determining a object's type dynamically then using the type in generics.

This will work because I'm specifying DateTime explicitly hardcoded as the type:

string serializedObject = JsonConvert.SerializeObject(exampleObject);
Type dataType = exampleObject.GetType();
JObject jObject = JObject.Parse(serializedObject);
jObject.Value<DateTime>("propertyName");

However neither of these seem to work:

jObject.Value<typeof(dateType)>("propertyName");
jObject.Value<dateType>("propertyName");

How can I specify the type of an property correctly here:

jObject.Value<{WHAT SHOULD I PUT HERE}>("propertyName");

It doesn't work because you are determining the dataType at runtime, however, Value<> needs to know the type at compile time. For one thing Value<T> might have constraints on what T must be, and it can't perform these checks at compile time on dataType if it doesn't know what dataType will be.

Here are some answers that address what you are trying to accomplish, although dealing with collections, applies to runtime determined generic parameters in general: Specifying generic collection type param at runtime

Note that your "{WHAT SHOULD I PUT HERE}" is what they are calling the generic parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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