user1675891
user1675891

Reputation:

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?

Upvotes: 0

Views: 5369

Answers (3)

Marco Klein
Marco Klein

Reputation: 699

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

Upvotes: 1

Konrad Viltersten
Konrad Viltersten

Reputation: 39118

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.

Upvotes: 1

Johan Larsson
Johan Larsson

Reputation: 17580

You can try this:

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

Upvotes: 1

Related Questions