Skip to content

Instantly share code, notes, and snippets.

@richlander
Created December 4, 2018 16:29
Show Gist options
  • Save richlander/dfb7fcfc78859ba90ee2fe99c4c219c1 to your computer and use it in GitHub Desktop.
Save richlander/dfb7fcfc78859ba90ee2fe99c4c219c1 to your computer and use it in GitHub Desktop.
Example Utf8JsonReaderLoop Usage
public static void Utf8JsonReaderLoop(ReadOnlySpan<byte> dataUtf8)
{
var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default);
while (json.Read())
{
JsonTokenType tokenType = json.TokenType;
ReadOnlySpan<byte> valueSpan = json.ValueSpan;
switch (tokenType)
{
case JsonTokenType.StartObject:
case JsonTokenType.EndObject:
break;
case JsonTokenType.StartArray:
case JsonTokenType.EndArray:
break;
case JsonTokenType.PropertyName:
break;
case JsonTokenType.String:
string valueString = json.GetStringValue();
break;
case JsonTokenType.Number:
if (!json.TryGetInt32Value(out int valueInteger))
{
throw new FormatException();
}
break;
case JsonTokenType.True:
case JsonTokenType.False:
bool valueBool = json.GetBooleanValue();
break;
case JsonTokenType.Null:
break;
default:
throw new ArgumentException();
}
}
dataUtf8 = dataUtf8.Slice((int)json.BytesConsumed);
JsonReaderState state = json.CurrentState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment