Search code examples
c#windows-phone-7streamdatacontractserializer

How can I convert a string to a stream?


I would like to parse some JSON:

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(STMsgObj));
            STMsgObj[] messages = (STMsgObj[])serializer.ReadObject(stream);

            foreach(STMsgObj aMsg in messages){
                MessageBox.Show(aMsg.body, "Data Passed", MessageBoxButton.OK); 
            }
        }
    }

How can I convert e.Result into a stream?

Exception:

System.InvalidCastException was unhandled
  Message=InvalidCastException
  StackTrace:
       at StockTwits.ViewModels.StreamPage.webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
       at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
       at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
       at System.Delegate.DynamicInvokeOne(Object[] args)
       at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
       at System.Delegate.DynamicInvoke(Object[] args)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
       at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
       at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
       at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
       at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

Solution

  • Try the following:

    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
    {
        // Your code here, using stream.
    }