Deserializing as DataContract from string value in memory

519 views Asked by At

I have the following code (which works) to deserialize raw json received from a web call :

public static async Task<Example> GetExample() {
    Example record = new Example();

    using ( WebClient wc = new WebClient() ) {
        wc.Headers.Add( "Accept", "application/json" );

        try {
            DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Example ) );
            using ( Stream s = await wc.OpenReadTaskAsync( "https://example.com/sample.json" ) ) {
                record = ser.ReadObject( s ) as Example;
            }
        } catch ( SerializationException se ) {
            Debug.WriteLine( se.Message );
        } catch ( WebException we ) {
            Debug.WriteLine( we.Message );
        } catch ( Exception e ) {
            Debug.WriteLine( e.Message );
        }
    }
    return record;
}

However, I have a different scenario where the data I am working with is encrypted so I need to decode base64, then decrypt the result to get the json data.

To keep it simple, assume that the following is the string received from the server ( base64 encoded only ) :

 ew0KICAidG9tIjogIjEyMyINCn0=

Which decodes with (stored in foo)

 string foo = Convert.FromBase64String("ew0KICAidG9tIjogIjEyMyINCn0=");

How do I pass foo to .ReadObject() as .ReadObject() only accepts Stream

2

There are 2 answers

2
zmbq On BEST ANSWER

Write it back into a stream and pass the stream to ReadObject. You can use a MemoryStream as is described here .

Following is an example as an anonymous type method :

/// <summary>
/// Read json from string into class with DataContract properties
/// </summary>
/// <typeparam name="T">DataContract class</typeparam>
/// <param name="json">JSON as a string</param>
/// <param name="encoding">Text encoding format (example Encoding.UTF8)</param>
/// <param name="settings">DataContract settings (can be used to set datetime format, etc)</param>
/// <returns>DataContract class populated with serialized json data</returns>
public static T FromString<T>( string json, Encoding encoding, DataContractJsonSerializerSettings settings ) where T : class {
    T result = null;
    try {
        DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( T ), settings );
        using ( Stream s = new MemoryStream( ( encoding ?? Encoding.UTF8 ).GetBytes( json ?? "" ) ) ) {
            result = ser.ReadObject( s ) as T;
        }
    } catch ( SerializationException se ) {
        Debug.WriteLine( se.Message );
    } catch ( Exception e ) {
        Debug.WriteLine( e.Message );
    }
    return result;
}
2
Graffito On

Try yhis:

using ( Stream s = await wc.OpenReadTaskAsync( "https://example.com/sample.json" ) ) 
{
    string str = Encoding.UTF8.GetString(s.GetBuffer(),0 , s.GetBuffer().Length)
    string foo = Convert.FromBase64String(str);
}