Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,49 +32,61 @@ public static void Run()
Console.WriteLine($"String in buffer is: {Encoding.UTF8.GetString(buffer)}");

// Search for "Summary" property name
while (reader.TokenType != JsonTokenType.PropertyName || !reader.ValueTextEquals("Summary"))
var foundSummary = false;
while (reader.Read() || GetMoreBytesFromStream(stream, ref buffer, ref reader))
{
if (!reader.Read())
if (reader.TokenType == JsonTokenType.PropertyName &&
reader.ValueTextEquals("Summary"))
{
// Not enough of the JSON is in the buffer to complete a read.
GetMoreBytesFromStream(stream, ref buffer, ref reader);
foundSummary = true;
break;
}
}

// Found the "Summary" property name.
Console.WriteLine($"String in buffer is: {Encoding.UTF8.GetString(buffer)}");
while (!reader.Read())
if (foundSummary)
{
// Not enough of the JSON is in the buffer to complete a read.
GetMoreBytesFromStream(stream, ref buffer, ref reader);
// Found the "Summary" property name.
Console.WriteLine($"String in buffer is: {Encoding.UTF8.GetString(buffer)}");
if (!reader.Read() && (!GetMoreBytesFromStream(stream, ref buffer, ref reader) || !reader.Read()))
throw new Exception("Invalid JSON");

// Display value of Summary property, that is, "Hot".
Console.WriteLine($"Got property value: {reader.GetString()}");
}
// Display value of Summary property, that is, "Hot".
Console.WriteLine($"Got property value: {reader.GetString()}");
}

private static void GetMoreBytesFromStream(
private static bool GetMoreBytesFromStream(
MemoryStream stream, ref byte[] buffer, ref Utf8JsonReader reader)
{
// If we've reached the end of the JSON data, return false.
if (reader.IsFinalBlock)
return false;
int bytesRead;
if (reader.BytesConsumed < buffer.Length)
{
ReadOnlySpan<byte> leftover = buffer.AsSpan((int)reader.BytesConsumed);

if (leftover.Length == buffer.Length)
{
Array.Resize(ref buffer, buffer.Length * 2);
Console.WriteLine($"Increased buffer size to {buffer.Length}");
}


// Move any leftover bytes to the beginning of the buffer.
leftover.CopyTo(buffer);
// Read more data from the stream to fill the rest of the buffer.
bytesRead = stream.Read(buffer.AsSpan(leftover.Length));
}
else
{
bytesRead = stream.Read(buffer);
}
// If we've reached the end of the stream, set isFinalBlock to true.
if (stream.Position == stream.Length)
Array.Resize(ref buffer, buffer.Length - (int)reader.BytesConsumed + bytesRead);
Console.WriteLine($"String in buffer is: {Encoding.UTF8.GetString(buffer)}");
reader = new Utf8JsonReader(buffer, isFinalBlock: bytesRead == 0, reader.CurrentState);
reader = new Utf8JsonReader(buffer, isFinalBlock: stream.Position == stream.Length, reader.CurrentState);
return bytesRead > 0;
}
}
}