forked from ZeraGmbH/Blockly.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonUtils.cs
More file actions
68 lines (62 loc) · 2.59 KB
/
Copy pathJsonUtils.cs
File metadata and controls
68 lines (62 loc) · 2.59 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
59
60
61
62
63
64
65
66
67
68
using System.Text.Json;
using System.Text.Json.Nodes;
namespace BlocklyNet;
/// <summary>
///
/// </summary>
public static class JsonUtils
{
/// <summary>
/// Configure serializer to generate camel casing.
/// </summary>
/// <remarks>
/// Can be customized if consumer uses customized serializsation rules.
/// </remarks>
#pragma warning disable CA2211 // Non-constant fields should not be visible
public static JsonSerializerOptions JsonSettings = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
#pragma warning restore CA2211 // Non-constant fields should not be visible
/// <summary>
/// Extract a scalar value from a JsonElement.
/// </summary>
/// <param name="json">As parsed with the System.Text.Json library.</param>
/// <returns>The value.</returns>
public static object? ToJsonScalar(this JsonElement json)
=> json.ValueKind switch
{
JsonValueKind.False => false,
JsonValueKind.Null => null,
JsonValueKind.Number => json.Deserialize<double>(),
JsonValueKind.String => json.Deserialize<string>(),
JsonValueKind.True => true,
_ => (object?)json,
};
/// <summary>
/// Extract a scalar value from a JsonElement.
/// </summary>
/// <param name="json">As parsed with the System.Text.Json library.</param>
/// <returns>The value.</returns>
public static object? ToJsonScalar(this JsonNode json)
=> json.GetValueKind() switch
{
JsonValueKind.False => false,
JsonValueKind.Null => null,
JsonValueKind.Number => json.GetValue<double>(),
JsonValueKind.String => json.GetValue<string>(),
JsonValueKind.True => true,
_ => (object?)json,
};
/// <summary>
/// Deserialize a JSON element to an instance.
/// </summary>
/// <typeparam name="T">Type of the instance.</typeparam>
/// <param name="node">Element to deserialize.</param>
/// <returns>Instance - may be null if JSON element represents null.</returns>
public static T? DefaultDeserialize<T>(this JsonNode node) => JsonSerializer.Deserialize<T>(node, JsonSettings);
/// <summary>
/// Deserialize a JSON element to an instance.
/// </summary>
/// <typeparam name="T">Type of the instance.</typeparam>
/// <param name="element">Element to deserialize.</param>
/// <returns>Instance - may be null if JSON element represents null.</returns>
public static T? DefaultDeserialize<T>(this JsonElement element) => JsonSerializer.Deserialize<T>(element, JsonSettings);
}