JsonSerializer无法从StreamReader读取流 [英] JsonSerializer can't read stream from StreamReader

查看:256
本文介绍了JsonSerializer无法从StreamReader读取流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取 DataContractJsonSerializer 对象来吞噬我的流.在注释行处于活动状态时执行代码时,可以看到提供的文本(它是可解析的JSON对象),因此我知道流可以正常工作.

I can't get the DataContractJsonSerializer object to swallow my stream. When I execute the code with the commented-out line active, I get to see the text provided (and it is a parsable JSON object), so I know that the stream is working fine.

但是,出于某种原因,编译器抱怨我试图将 ReadObject 中的 streamReader 简化为 > Stream .好吧,不是吗?!

However, for some reason, the compiler complains that the streamReader I'm trying to shove down its throat in ReadObject isn't a Stream. Well, isn't it?!

参数1:无法从"System.IO.StreamReader"转换为"System.IO.Stream"

Argument 1: cannot convert from 'System.IO.StreamReader' to 'System.IO.Stream'

我缺少什么以及如何解决?

What am I missing and how do I resolve it?

using (StreamReader streamReader = new StreamReader(...))
{
  //String responseText = reader.ReadToEnd();
  MyThingy thingy = new MyThingy();
  DataContractJsonSerializer serializer 
    = new DataContractJsonSerializer(thingy.GetType());
  thingy = serializer.ReadObject(streamReader);
}

我正在适应

I'm adapting this example to work with my stream. Should I approach it from a different angle? If so - how?

推荐答案

您正试图放入流的阅读器而不是实际的流.跳过using,任何隐藏在省略号后面的内容(即创建StreamReader实例时作为参数输入的内容),都可以将其放入ReadObject.

You're trying to put in a reader of a stream instead of an actual stream. Skip the using and whatever hides behind the ellipsis (i.e. whatever you put in as an argument when you create an instance of StreamReader), you can probably put that into the ReadObject.

此外,读取数据时也会遇到问题,因为ReadObject将返回类型为Object的实例,并且需要将其转换为MyThingy.由于它是可为空的(我假设),因此您不必键入强制转换,而是对其进行形式化.

Also, you'll get into problems when reading the data because ReadObject will return an instance of type Object and you'll need to convert it into MyThingy. Since it's a nullable (I'm assuming), you don't have to type cast but rather as-ify it.

MyThingy thingy = new MyThingy();
DataContractJsonSerializer serializer 
  = new DataContractJsonSerializer(thingy.GetType());
Stream stream = ...;
thingy = serializer.ReadObject(stream) as MyThingy;

您当然可以跳过倒数第二行,并将流直接放入最后一行.

You could of course skip the next-to-last line and put the stream directly into the last line.

@JohanLarsson的礼貌(所有瑞典人都很伟大,尤其是像我这样来自斯德哥尔摩的瑞典人):
如果您无法或不想在using语句中省略StreamReader声明,我建议您看一下BaseStream属性以获取它.

Courtesy of @JohanLarsson (all Swedes are great, especially those from Stockholm, like me):
In case you can't or don't want to omit the StreamReader declaration in your using statement, I'd suggest that you take a look at BaseStream property to get to it.

这篇关于JsonSerializer无法从StreamReader读取流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆