JsonSerializer 无法从 StreamReader 读取流 [英] JsonSerializer can't read stream from 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.
但是,由于某种原因,编译器抱怨 streamReader
我试图在 ReadObject
中塞住它的喉咙 不是 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
实例时作为参数放入的任何内容),您可能可以将其放入 读取对象
.
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
.由于它是可空的(我假设),因此您不必键入强制转换,而是对其进行 as-ify.
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屋!