Anonymous type in method for Deserializing json from a string to DataContract

139 Views Asked by At

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 :

error

How can this be adjusted without hard-coding the type so that it works as I intend ?

1

There are 1 best solutions below

3
On BEST ANSWER

The as keyword implies that the type is a reference type, and not a value type. You cannot store null in a value type. Thus, you either need to restrict the type T to a reference type:

public T Json2Object<T>(string json, Encoding encoding) where T : class {
    // ...
}

Or cast rather than use as:

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 = (T)ser.ReadObject( s );
    }
    return result;
}