-
Notifications
You must be signed in to change notification settings - Fork 368
/
JsonElementExtensions.cs
54 lines (48 loc) · 1.63 KB
/
JsonElementExtensions.cs
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Text.Json;
namespace Microsoft.DotNet.Interactive.Jupyter.Messaging;
public static class JsonElementExtensions
{
public static object ToObject(this JsonElement source)
{
return source.ValueKind switch
{
JsonValueKind.String => source.GetString(),
JsonValueKind.False => false,
JsonValueKind.True => true,
JsonValueKind.Number => source.GetDouble(),
JsonValueKind.Object => source.ToDictionary(),
JsonValueKind.Array => source.ToArray(),
_ => null
};
}
public static IReadOnlyDictionary<string, object> ToReadOnlyDictionary(this JsonElement source)
{
var ret = new Dictionary<string, object>();
foreach (var value in source.EnumerateObject())
{
ret[value.Name] = value.Value.ToObject();
}
return ret;
}
public static IDictionary<string, object> ToDictionary(this JsonElement source)
{
var ret = new Dictionary<string, object>();
foreach (var value in source.EnumerateObject())
{
ret[value.Name] = value.Value.ToObject();
}
return ret;
}
public static object[] ToArray(this JsonElement source)
{
var ret = new List<object>();
foreach (var value in source.EnumerateArray())
{
ret.Add(value.ToObject());
}
return ret.ToArray();
}
}