简体   繁体   中英

JsonSerializer can't read stream from StreamReader

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?

You can try this:

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

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 (ie 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.

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);
 }   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM