What is the correct way to use JSON.NET to parse stream of JSON objects?
I think if you change your loop around slightly everything should work:
public IEnumerable<TResult> ReadJson<TResult>(Stream stream)
{
var serializer = new JsonSerializer();
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
{
jsonReader.SupportMultipleContent = true;
while (jsonReader.Read())
{
yield return serializer.Deserialize<TResult>(jsonReader);
}
}
}
Note that you must iterate over the IEnumerable<TResult>
while the Stream
passed to this method is open:
using (var stream = /* some stream */)
{
IEnumerable<MyClass> result = ReadJson<MyClass>(stream);
foreach (var item in result)
{
Console.WriteLine(item.MyProperty);
}
}
Example: https://dotnetfiddle.net/Y2FLuK
Sample on JsonNet site: Read Multiple Fragments With JsonReader