I have heard that Json.NET is faster than DataContractJsonSerializer, and wanted to give it a try...
But I couldn't find any methods on JsonConvert that take a stream rather than a string.
For deserializing a file containing JSON on WinPhone, for example, I use the following code to read the file contents into a string, and then deserialize into JSON. It appears to be about 4 times slower in my (very ad-hoc) testing than using DataContractJsonSerializer to deserialize straight from the stream...
// DCJS
DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(Constants));
Constants constants = (Constants)dc.ReadObject(stream);
// JSON.NET
string json = new StreamReader(stream).ReadToEnd();
Constants constants = JsonConvert.DeserializeObject<Constants>(json);
Am I doing it wrong?
UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).
Use the
JsonTextReader
class with aStreamReader
or use theJsonSerializer
overload that takes aStreamReader
directly:I arrived at this question looking for a way to stream an open ended list of objects onto a
System.IO.Stream
and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)@Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.
Note that you may receive an exception when the
AnonymousPipeServerStream
is disposed, I ignored this as it isn't relevant to the problem at hand.The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
Documentation: Deserialize JSON from a file stream
I've written an extension class to help me deserializing from JSON sources (string, stream, file).
Deserializing is now as easy as writing:
Hope it will help someone else.