JsonSerializer can't read stream from StreamReader

匆匆过客 提交于 2019-12-12 02:42:04

问题


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.

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?!

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?


回答1:


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.

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.

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.




回答2:


You can try this:

using (StreamReader streamReader = new StreamReader(...))
{
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyThingy));
  MyThingy thingy = (MyThingy) serializer.ReadObject(streamReader.BaseStream);
}



回答3:


I've been always using this:

 // get stuff here
 String json = GetJSON();

 List<T> result;
 using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
 {
      var serializer = new DataContractJsonSerializer(typeof(List<T>));
      result = (List<T>)serializer.ReadObject(ms);
 }   


来源:https://stackoverflow.com/questions/14081550/jsonserializer-cant-read-stream-from-streamreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!