jtr/DevDisciples.Json.Tools/JsonFormatter.cs
mdnapo 82a59eebd2 - Refactored code
- Implemented basic JSON Path interpreter
- Clean up
2024-09-22 16:30:31 +02:00

95 lines
3.2 KiB
C#

using DevDisciples.Json.Parser;
using DevDisciples.Json.Parser.Syntax;
using DevDisciples.Parsing;
namespace DevDisciples.Json.Tools;
public static partial class JsonFormatter
{
private static VisitorContainer<IJsonSyntax, Context> Visitors { get; } = new();
static JsonFormatter()
{
Visitors.Register<JsonArraySyntax>(PrintArray);
Visitors.Register<JsonObjectSyntax>(PrintObject);
Visitors.Register<JsonStringSyntax>(PrintString);
Visitors.Register<JsonNumberSyntax>(PrintNumber);
Visitors.Register<JsonBoolSyntax>(PrintBool);
Visitors.Register<JsonNullSyntax>(PrintNull);
}
public static string Format(string source, Context? context)
{
var node = JsonParser.Parse("<source>", source);
return Format(node, context);
}
public static string Format(IJsonSyntax visitee, Context? context = null)
{
context ??= new();
Visitors[visitee.GetType()](visitee, context);
return context.Builder.ToString();
}
private static void PrintArray(IJsonSyntax visitee, Context context)
{
var array = (JsonArraySyntax)visitee;
context.Builder.Append($"[{context.NewLine}");
context.IncrementDepth();
for (var i = 0; i < array.Elements.Length; i++)
{
var node = array.Elements[i];
context.Builder.Append(context.Indent);
Visitors[node.GetType()](node, context);
if (i < array.Elements.Length - 1) context.Builder.Append($",{context.NewLine}");
}
context.DecrementDepth();
context.Builder.Append($"{context.NewLine}{context.Indent}]");
}
private static void PrintObject(IJsonSyntax visitee, Context context)
{
var @object = (JsonObjectSyntax)visitee;
context.Builder.Append($"{{{context.NewLine}");
context.IncrementDepth();
var count = @object.Properties.Length;
for (var i = 0; i < count; i++)
{
var property = @object.Properties.ElementAt(i);
context.Builder.Append($"{context.Indent}\"{property.Key.Lexeme}\":{context.Space}");
Visitors[property.Value.GetType()](property.Value, context);
if (i < count - 1) context.Builder.Append($",{context.NewLine}");
}
context.DecrementDepth();
context.Builder.Append($"{context.NewLine}{context.Indent}}}");
}
private static void PrintString(IJsonSyntax visitee, Context context)
{
var @string = (JsonStringSyntax)visitee;
context.Builder.Append($"\"{@string.Token.Lexeme}\"");
}
private static void PrintNumber(IJsonSyntax visitee, Context context)
{
var number = (JsonNumberSyntax)visitee;
context.Builder.Append($"{number.Value}");
}
private static void PrintBool(IJsonSyntax visitee, Context context)
{
var @bool = (JsonBoolSyntax)visitee;
context.Builder.Append($"{@bool.Value.ToString().ToLower()}");
}
private static void PrintNull(IJsonSyntax visitee, Context context)
{
context.Builder.Append("null");
}
}