I am trying to write an anonymous method for the purpose of deserializing Json to a DataContract. This would allow me to have something re-usable without having to write the same code for each DataContract class I wrote for each json query.
The code I have so far, is as follows :
public T Json2Object<T>(string json, Encoding encoding) {
T result;
DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( T ) );
using ( Stream s = new MemoryStream( ( encoding ?? Encoding.UTF8 ).GetBytes( json ?? "" ) ) ) {
result = ser.ReadObject( s ) as T;
}
return result;
}
It is giving me errors in the IDE as follows :
How can this be adjusted without hard-coding the type so that it works as I intend ?
The
as
keyword implies that the type is a reference type, and not a value type. You cannot storenull
in a value type. Thus, you either need to restrict the typeT
to a reference type:Or cast rather than use
as
: