Forge
csharpc88715b7
1using System.Text.Json;
2using System.Text.Json.Nodes;
3using Json.Schema;
4
5namespace AIGuiders.DotnetTools.TomlCheck;
6
7internal sealed class JsonSchemaValidator(string schemaPath)
8{
9 private readonly JsonSchema _schema = JsonSchema.FromFile(schemaPath);
10
11 public bool TryValidate(JsonNode document, out IReadOnlyList<string> errors)
12 {
13 var element = document.Deserialize<JsonElement>();
14 var result = _schema.Evaluate(element, new EvaluationOptions
15 {
16 OutputFormat = OutputFormat.List,
17 });
18
19 if (result.IsValid)
20 {
21 errors = [];
22 return true;
23 }
24
25 errors = CollectErrors(result);
26 return false;
27 }
28
29 private static List<string> CollectErrors(EvaluationResults result)
30 {
31 var list = new List<string>();
32 Walk(result, list);
33 return list;
34 }
35
36 private static void Walk(EvaluationResults node, List<string> errors)
37 {
38 if (node.Errors is { Count: > 0 })
39 {
40 var location = string.IsNullOrWhiteSpace(node.EvaluationPath.ToString())
41 ? "$"
42 : node.EvaluationPath.ToString();
43 foreach (var (key, message) in node.Errors)
44 errors.Add($"{location}: {key} — {message}");
45 }
46
47 if (node.Details is null)
48 return;
49
50 foreach (var child in node.Details)
51 Walk(child, errors);
52 }
53}
54
View only · write via MCP/CIDE