如何将字符串转换为流?

发布于 2024-10-02 23:54:09 字数 2253 浏览 5 评论 0原文

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

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦毁影碎の 2024-10-09 23:54:09

请尝试以下操作:

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

Try the following:

using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
    // Your code here, using stream.
}
你爱我像她 2024-10-09 23:54:09

请改为调用 DownloadDataAsync

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

如果您确实想坚持使用 DownloadStringAsync,可以传递 XmlReader.Create(new StringReader(e.Result))

Call DownloadDataAsync instead.

You can then pass new MemoryStream(e.Result) from the DownloadDataCompleted event.

If you really want to stick with DownloadStringAsync, you can pass XmlReader.Create(new StringReader(e.Result)).

厌味 2024-10-09 23:54:09

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

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

Given that WebClient wraps an API that is already stream based means there are a number of unnecessary conversions. You might want to consider swapping your WebClient for plain old HttpWebRequest, which hands you a stream out of the box.

HttpWebRequest req=(HttpWebRequest)WebRequest.Create(myUrl);
using(var resp=req.GetResponse())
using(var stream=resp.GetResponseStream())
{
    ...
}
今天小雨转甜 2024-10-09 23:54:09

您的 JSON 数据不是数组。

Your JSON data isn't an array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文