Skip to content

Commit

Permalink
shorten valuetextequals example
Browse files Browse the repository at this point in the history
  • Loading branch information
tdykstra committed Jan 8, 2020
1 parent de6d0e9 commit 3cf8e52
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions snippets/core/system-text-json/csharp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace SystemTextJsonSamples
Expand Down Expand Up @@ -105,6 +107,8 @@ static async Task Main(string[] args)

Console.WriteLine("\n============================= Utf8Reader from file\n");
Utf8ReaderFromFile.Run();
string jsonString = File.ReadAllText("Universities.json");

This comment has been minimized.

Copy link
@ahsonkhan

ahsonkhan Jan 8, 2020

Member

nit: put a new line in between the previous and next run (between line 109 and 110).

ValueTextEqualsExample.Run(Encoding.UTF8.GetBytes(jsonString));

Console.WriteLine("\n============================= Utf8Reader from byte array\n");
Utf8ReaderFromBytes.Run();
Expand Down
41 changes: 41 additions & 0 deletions snippets/core/system-text-json/csharp/ValueTextEqualsExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;

namespace SystemTextJsonSamples
{
public class ValueTextEqualsExample
{
// <SnippetDefineUtf8Var>
private static readonly byte[] s_nameUtf8 = Encoding.UTF8.GetBytes("name");
// </SnippetDefineUtf8Var>
public static void Run(ReadOnlySpan<byte> jsonReadOnlySpan)
{
int count = 0;
int total = 0;
var reader = new Utf8JsonReader(jsonReadOnlySpan);

// <SnippetUseUtf8Var>
while (reader.Read())
{
JsonTokenType tokenType = reader.TokenType;

switch (tokenType)
{
case JsonTokenType.StartObject:
total++;
break;
case JsonTokenType.PropertyName:
if (reader.ValueTextEquals(s_nameUtf8))
{
count++;
}
break;
}
// </SnippetUseUtf8Var>
}
Console.WriteLine($"{count} out of {total} have \"name\" properties");
}
}
}

0 comments on commit 3cf8e52

Please sign in to comment.