2022-08-13 13:01:47 -07:00

209 lines
9.2 KiB
C#

using System.Text;
namespace Json2CSharpCodeGenerator.Lib.CodeWriters;
public class DartCodeWriter : ICodeBuilder
{
public string FileExtension => throw new NotImplementedException();
public string DisplayName => throw new NotImplementedException();
public IReadOnlyCollection<string> ReservedKeywords => throw new NotImplementedException();
public string GetTypeName(JsonType type, IJsonClassGeneratorConfig config)
{
return type.Type switch
{
//case JsonTypeEnum.Anything: return "object"; // Later, test to do
JsonTypeEnum.Array => GetCollectionTypeName(elementTypeName: GetTypeName(type.InternalType, config), config.CollectionType),
// case JsonTypeEnum.Dictionary: return "Dictionary<string, " + this.GetTypeName(type.InternalType, config) + ">";
JsonTypeEnum.Boolean => "bool?",
JsonTypeEnum.Float => "double?",
JsonTypeEnum.Integer => "int?",
JsonTypeEnum.Long => "double?",
JsonTypeEnum.Date => "DateTime?",
//case JsonTypeEnum.NonConstrained: return "object"; // Later, test to do
//case JsonTypeEnum.NullableBoolean: return "bool?";
//case JsonTypeEnum.NullableFloat: return "double?";
//case JsonTypeEnum.NullableInteger: return "int?";
//case JsonTypeEnum.NullableLong: return "long?";
//case JsonTypeEnum.NullableDate: return "DateTime?";
//case JsonTypeEnum.NullableSomething: return "object";
JsonTypeEnum.Object => type.NewAssignedName + "?",
JsonTypeEnum.String => "String?",
_ => throw new NotSupportedException("Unsupported json type: " + type.Type),
};
}
public string GetTypeFunctionName(JsonType type, IJsonClassGeneratorConfig config)
{
return type.Type switch
{
JsonTypeEnum.Anything => "",
JsonTypeEnum.Array => "[" + type.InternalType.NewAssignedName + ".from_dict(y) for y in {0}]",
// case JsonTypeEnum.Dictionary: return "Dictionary<string, " + this.GetTypeName(type.InternalType, config) + ">";
JsonTypeEnum.Boolean => "",
JsonTypeEnum.Float => "float({0})",
JsonTypeEnum.Integer => "int({0})",
JsonTypeEnum.Long => "float({0})",
//case JsonTypeEnum.Date: return "DateTime"; // Do Later
JsonTypeEnum.Date => "str({0})",
JsonTypeEnum.NonConstrained => "",
// case JsonTypeEnum.NullableBoolean: return "bool?";
//case JsonTypeEnum.NullableFloat: return "double?";
//case JsonTypeEnum.NullableInteger: return "int?";
//case JsonTypeEnum.NullableLong: return "long?";
//case JsonTypeEnum.NullableDate: return "DateTime?";
//case JsonTypeEnum.NullableSomething: return "object";
JsonTypeEnum.Object => type.NewAssignedName + ".from_dict({0})",
JsonTypeEnum.String => "str({0})",
_ => throw new NotSupportedException("Unsupported json type: " + type.Type),
};
}
public bool IsReservedKeyword(string word) => throw new NotImplementedException();
public void WriteClass(IJsonClassGeneratorConfig config, StringBuilder sw, JsonType type)
{
string className = type.AssignedName;
_ = sw.AppendFormat("class {0} {{{1}", className, Environment.NewLine);
WriteClassMembers(config, sw, type, "");
_ = sw.AppendLine("}");
_ = sw.AppendLine();
}
public void WriteClassMembers(IJsonClassGeneratorConfig config, StringBuilder sw, JsonType type, string prefix)
{
StringBuilder fields = new();
StringBuilder fromJsonMapping = new();
StringBuilder toJsonMapping = new();
if (type.Fields.Any())
{
_ = fields.Append('{');
}
foreach (FieldInfo field in type.Fields)
{
_ = field.MemberName;
string propertyAttribute = field.JsonMemberName.RemoveSpecialCharacters().ToCamelCase();
string originalPropertyAttribute = field.JsonMemberName;
_ = sw.AppendFormat(" {0} {1};{2}", field.Type.GetTypeName(), propertyAttribute, Environment.NewLine);
_ = fields.Append("this." + propertyAttribute + ", ");
if (field.Type.Type == JsonTypeEnum.Array)
{
_ = fromJsonMapping.AppendLine(string.Format(" if (json['{0}'] != null) {{", originalPropertyAttribute));
_ = fromJsonMapping.AppendLine(string.Format(" {0} = <{1}>[];", propertyAttribute, field.Type.InternalType.NewAssignedName));
_ = fromJsonMapping.AppendLine(string.Format(" json['{0}'].forEach((v) {{", originalPropertyAttribute));
_ = fromJsonMapping.AppendLine(string.Format(" {0}!.add({1}.fromJson(v));", propertyAttribute, field.Type.InternalType.NewAssignedName));
_ = fromJsonMapping.AppendLine(" });");
_ = fromJsonMapping.AppendLine(" }");
_ = toJsonMapping.AppendLine(string.Format(" data['{0}'] ={0} != null ? {1}!.map((v) => v?.toJson()).toList() : null;", originalPropertyAttribute, propertyAttribute));
}
else if (field.Type.Type == JsonTypeEnum.Object)
{
_ = fromJsonMapping.AppendLine(string.Format(" {1} = json['{0}'] != null ? {2}.fromJson(json['{0}']) : null;", originalPropertyAttribute, propertyAttribute, field.Type.GetTypeName()));
_ = toJsonMapping.AppendLine(string.Format(" data['{0}'] = {1}!.toJson();", originalPropertyAttribute, propertyAttribute));
}
else
{
_ = fromJsonMapping.AppendLine(string.Format(" {1} = json['{0}'];", originalPropertyAttribute, propertyAttribute));
_ = toJsonMapping.AppendLine(string.Format(" data['{0}'] = {1};", originalPropertyAttribute, propertyAttribute));
}
}
if (type.Fields.Any())
{
// Remove trailing comma
fields.Length--;
fields.Length--;
_ = fields.Append('}');
}
if (!config.RemoveConstructors)
{
// Create Class Constructor
_ = sw.AppendLine();
_ = sw.AppendLine(string.Format(" {0}({1}); {2}", type.AssignedName, fields.ToString(), Environment.NewLine));
}
if (type.Fields.Any())
{
if (!config.RemoveFromJson)
{
// Add From Json Function
_ = sw.AppendLine(string.Format(" {0}.fromJson(Map<String, dynamic> json) {{", type.AssignedName));
_ = sw.Append(fromJsonMapping.ToString());
_ = sw.AppendLine(" }");
_ = sw.AppendLine();
}
if (!config.RemoveToJson)
{
// Add To Json Function
_ = sw.AppendLine(" Map<String, dynamic> toJson() {");
_ = sw.AppendLine(" final Map<String, dynamic> data = Map<String, dynamic>();");
_ = sw.Append(toJsonMapping.ToString());
_ = sw.AppendLine(" return data;");
_ = sw.AppendLine(" }");
}
}
}
public void WriteDeserializationComment(IJsonClassGeneratorConfig config, StringBuilder sw, bool rootIsArray = false)
{
return;
}
public void WriteFileEnd(IJsonClassGeneratorConfig config, StringBuilder sw)
{
// sw.Insert(0, "import json" + Environment.NewLine);
// sw.Insert(0, "from dataclasses import dataclass" + Environment.NewLine);
// sw.Insert(0, "from typing import Any" + Environment.NewLine);
// if (sw.ToString().Contains("List"))
// sw.Insert(0, string.Format("from typing import List{0}", Environment.NewLine));
return;
}
public void WriteFileStart(IJsonClassGeneratorConfig config, StringBuilder sw)
{
_ = sw.AppendLine("/* ");
_ = sw.AppendLine("// Example Usage");
_ = sw.AppendLine("Map<String, dynamic> map = jsonDecode(<myJSONString>);");
_ = sw.AppendLine("var myRootNode = Root.fromJson(map);");
_ = sw.AppendLine("*/ ");
return;
}
public void WriteNamespaceEnd(IJsonClassGeneratorConfig config, StringBuilder sw, bool root)
{
return;
}
public void WriteNamespaceStart(IJsonClassGeneratorConfig config, StringBuilder sw, bool root)
{
return;
}
private static string GetCollectionTypeName(string elementTypeName, OutputCollectionType type)
{
return type switch
{
//case OutputCollectionType.Array: return elementTypeName + "[]";
OutputCollectionType.Array => elementTypeName + "[]",
OutputCollectionType.MutableList => "List<" + elementTypeName + ">?",
// case OutputCollectionType.IReadOnlyList: return "IReadOnlyList<" + elementTypeName + ">";
// case OutputCollectionType.ImmutableArray: return "ImmutableArray<" + elementTypeName + ">";
_ => throw new ArgumentOutOfRangeException(paramName: nameof(type), actualValue: type, message: "Invalid " + nameof(OutputCollectionType) + " enum value."),
};
}
}