如何将字符串转换为流?

时间:2010-11-16 18:16:08

标签: c# windows-phone-7 stream datacontractserializer

我想解析一些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); 
            }
        }
    }

如何将e.Result转换为流?

例外:

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)

4 个答案:

答案 0 :(得分:6)

尝试以下方法:

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

答案 1 :(得分:0)

改为呼叫DownloadDataAsync

然后,您可以从new MemoryStream(e.Result)事件传递DownloadDataCompleted

如果你真的想坚持DownloadStringAsync,你可以通过XmlReader.Create(new StringReader(e.Result))

答案 2 :(得分:0)

鉴于WebClient包装已经基于流的API意味着存在许多不必要的转换。您可能需要考虑将WebClient替换为普通旧HttpWebRequest,这样就可以开箱即用。

HttpWebRequest req=(HttpWebRequest)WebRequest.Create(myUrl);
using(var resp=req.GetResponse())
using(var stream=resp.GetResponseStream())
{
    ...
}

答案 3 :(得分:0)

您的JSON数据不是数组。