manas sahu manas sahu - 1 year ago 208
C# Question

System.RuntimeType doesn't contain a definition for Declared Properties

I am trying to Deserialize Json string to object in debug mode its working fine but at release mode throwing error such that System.RuntimeType doesn't contain a definition for Declared Properties...

Any Help Would Be Appreciated

public T DeserializeJSon<T>(string jsonString)
dynamic dT = typeof(T);

if (dT.Name.EndsWith("List"))
dT = dT.DeclaredProperties[0].PropertyType.GenericTypeArguments[0];

DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings()
DateTimeFormat = new DateTimeFormat(DateTimeFormat),
UseSimpleDictionaryFormat = true
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T), settings);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(stream);

return obj;

Answer Source

DeclaredProperties is a member of System.TypeInfo, not of System.Type and least of all dyanmic.

Thus simply write this instead:

Type dt = typeof(T);
if (dT.Name.EndsWith("List"))
    dT = dT.GetTypeInfo().DeclaredProperties.First().PropertyType.GenericTypeArguments[0];

I strongly recommend not to use dyanmic unless you really need it (which isn´t the case here). Dynamic will only shift the actual error (in your case access to a member that doesn´t exist) to runtime instead of to the compiler which makes it harder to find errors. Another reason here is that you already know the runtime-type of the expression typeof(T), which is allways System.Type. Why should you want to hide this information by using dynamic?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download