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
Write it back into a stream and pass the stream to
ReadObject
. You can use aMemoryStream
as is described here .Following is an example as an anonymous type method :