-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonToken.cs
More file actions
58 lines (48 loc) · 1.57 KB
/
JsonToken.cs
File metadata and controls
58 lines (48 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Dynamic;
using System.Text.Json;
using Couchbase.Core.Json;
namespace Couchbase.Core.Internal;
internal sealed class JsonToken : IJsonToken
{
private readonly JsonElement _element;
private readonly JsonStreamReader _streamReader;
/// <summary>
/// Creates a new NewtonsoftJsonToken.
/// </summary>
/// <param name="element">The <seealso cref="JsonElement"/> to wrap.</param>
/// <param name="streamReader"><see cref="JsonStreamReader"/> to use for deserialization.</param>
public JsonToken(JsonElement element, JsonStreamReader streamReader)
{
_element = element;
_streamReader = streamReader ?? throw new ArgumentNullException(nameof(streamReader));
}
/// <inheritdoc />
public IJsonToken? this[string key]
{
get
{
if (_element.TryGetProperty(key, out var value) && value.ValueKind != JsonValueKind.Null)
{
return new JsonToken(value, _streamReader);
}
return null;
}
}
/// <inheritdoc />
public T ToObject<T>() => _streamReader.Deserialize<T>(_element)!;
/// <inheritdoc />
public T Value<T>()
{
if (_element.TryGetValue<T>(out var value))
{
return value!;
}
throw new InvalidOperationException($"Unable to convert {_element.ValueKind} to {typeof(T)}.");
}
/// <inheritdoc />
public dynamic ToDynamic() => new ExpandoObject();
public byte[] ToUtf8Bytes()
{
return System.Text.Encoding.UTF8.GetBytes(_element.GetRawText());
}
}