64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using DevDisciples.Json.Parser;
|
|
using DevDisciples.Parsing;
|
|
using Humanizer;
|
|
|
|
namespace DevDisciples.Json.Tools;
|
|
|
|
public static partial class Json2CSharpTranslator
|
|
{
|
|
public static class JsonArrayTranslator
|
|
{
|
|
public static ITranslation Translate(ISyntaxNode visitee, object[] args)
|
|
{
|
|
var context = ContextFromArgs(args);
|
|
var name = NameFromArgs(args);
|
|
var array = (JsonArray)visitee;
|
|
var type = "object";
|
|
|
|
if (array.Elements.All(e => e is JsonObject))
|
|
{
|
|
context.Classes.Add(SquashObjects(name, array.Elements, args));
|
|
type = context.Classes.Last().Name;
|
|
}
|
|
|
|
if (array.Elements.All(e => e is JsonString es && DateTime.TryParse(es.Value, out _)))
|
|
{
|
|
type = "DateTime";
|
|
}
|
|
else if (array.Elements.All(e => e is JsonString))
|
|
{
|
|
type = "string";
|
|
}
|
|
else if (array.Elements.All(e => e is JsonNumber))
|
|
{
|
|
type = array.Elements.Any(e => ((JsonNumber)e).Token.Lexeme.Contains('.')) ? "double" : "int";
|
|
}
|
|
|
|
return new PropertyTranslation
|
|
{
|
|
Type = $"List<{type}>",
|
|
Name = name,
|
|
};
|
|
}
|
|
|
|
private static ClassTranslation SquashObjects(string className, List<ISyntaxNode> objects, object[] args)
|
|
{
|
|
var classes = objects
|
|
.Select(@object => JsonObjectTranslator.Translate(@object, args))
|
|
.ToArray();
|
|
|
|
var squashed = new ClassTranslation
|
|
{
|
|
Name = className.Singularize(),
|
|
Properties = new()
|
|
};
|
|
|
|
foreach (var @class in classes)
|
|
foreach (var prop in ((ClassTranslation)@class).Properties)
|
|
if (squashed.Properties.All(p => p.Name != prop.Name))
|
|
squashed.Properties.Add(prop);
|
|
|
|
return squashed;
|
|
}
|
|
}
|
|
} |