Repository navigation
Expand file tree
/
Copy pathYamlConverter.cs
More file actions
73 lines (65 loc) · 2.56 KB
/
Copy pathYamlConverter.cs
File metadata and controls
73 lines (65 loc) · 2.56 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
69
70
71
72
73
// Copyright (c) The LEGO Group. All rights reserved.
namespace LEGO.AsyncAPI.Readers
{
using System;
using System.Globalization;
using System.Text.Json.Nodes;
using YamlDotNet.Core;
using YamlDotNet.RepresentationModel;
internal static class YamlConverter
{
public static JsonNode ToJsonNode(this YamlDocument yamlDocument, AsyncApiReaderSettings settings)
{
return yamlDocument.RootNode.ToJsonNode(settings);
}
public static JsonObject ToJsonObject(this YamlMappingNode yamlMappingNode, AsyncApiReaderSettings settings)
{
var node = new JsonObject();
foreach (var keyValuePair in yamlMappingNode)
{
var key = ((YamlScalarNode)keyValuePair.Key).Value!;
node[key] = keyValuePair.Value.ToJsonNode(settings);
}
return node;
}
public static JsonArray ToJsonArray(this YamlSequenceNode yaml, AsyncApiReaderSettings settings)
{
var node = new JsonArray();
foreach (var value in yaml)
{
node.Add(value.ToJsonNode(settings));
}
return node;
}
public static JsonNode ToJsonNode(this YamlNode yaml, AsyncApiReaderSettings settings)
{
return yaml switch
{
YamlMappingNode map => map.ToJsonObject(settings),
YamlSequenceNode seq => seq.ToJsonArray(settings),
YamlScalarNode scalar => scalar.ToJsonValue(settings),
_ => throw new NotSupportedException("This yaml isn't convertible to JSON"),
};
}
private static JsonValue ToJsonValue(this YamlScalarNode yaml, AsyncApiReaderSettings settings)
{
switch (yaml.Style)
{
case ScalarStyle.Plain:
return decimal.TryParse(yaml.Value, NumberStyles.Float, settings.CultureInfo, out var d)
? JsonValue.Create(d)
: bool.TryParse(yaml.Value, out var b)
? JsonValue.Create(b)
: JsonValue.Create(yaml.Value) !;
case ScalarStyle.SingleQuoted:
case ScalarStyle.DoubleQuoted:
case ScalarStyle.Literal:
case ScalarStyle.Folded:
case ScalarStyle.Any:
return JsonValue.Create(yaml.Value);
default:
throw new ArgumentOutOfRangeException();
}
}
}
}