Skip to content

Instantly share code, notes, and snippets.

@Craftplacer
Last active July 24, 2020 18:37
Show Gist options
  • Save Craftplacer/3151b64ab86ee929202eab8173e8a7fe to your computer and use it in GitHub Desktop.
Save Craftplacer/3151b64ab86ee929202eab8173e8a7fe to your computer and use it in GitHub Desktop.
Simple tool for making dart source code out of JSON files. (depends on Newtonsoft.Json and Humanizer)
using System;
using System.IO;
using System.Linq;
using System.Text;
using Humanizer;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Json2Dart
{
public static class Program
{
public static void Main(string[] args)
{
var outputMode = args.Contains("--output") || args.Contains("-o");
const string inputFilePath = "input.json";
const string outputFilePath = "output.dart";
while (true)
{
Console.Write("Enter class name: ");
var className = Console.ReadLine();
// Console.Clear();
// Console.WriteLine("Enter JSON (press Alt+Enter to return):");
// var json = ReadLines();
if (!File.Exists(inputFilePath))
{
Console.WriteLine("Couldn't find input file");
Environment.Exit(1);
}
var json = File.ReadAllText(inputFilePath);
var jObject = GetJObject(json);
Console.WriteLine("Converting...");
var dart = ToDart(jObject, className);
if (outputMode)
{
File.WriteAllText(outputFilePath, dart);
return;
}
Console.WriteLine("===== copy here~");
Console.WriteLine(dart);
Console.ReadLine();
}
}
private static JObject GetJObject(string json)
{
Console.WriteLine("Deserializing...");
var serializerSettings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
var jObject = (JObject) JsonConvert.DeserializeObject(json, serializerSettings);
return jObject;
}
private static string ToDart(JObject jObject, string className)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"class {className} {{");
foreach (var pair in jObject)
{
var key = pair.Key.Camelize();
var dartType = ToDartType(pair.Value);
var supported = IsJsonTypeSupported(pair.Value.Type);
AppendLine(stringBuilder, $"{dartType} {key};", 1, !supported);
}
stringBuilder.AppendLine();
AppendLine(stringBuilder, $"{className}.fromJson(Map<String, dynamic> json) {{", 1);
foreach (var pair in jObject)
{
var key = pair.Key.Camelize();
var supported = IsJsonTypeSupported(pair.Value.Type);
AppendLine(stringBuilder, $"{key} = json[\"{pair.Key}\"];", 2, !supported);
}
AppendLine(stringBuilder, "}", 1);
AppendLine(stringBuilder, "}");
return stringBuilder.ToString();
}
private static void AppendLine(StringBuilder sb, string value, int indent = 0, bool comment = false)
{
if (comment)
sb.Append("//");
sb.Append('\t', indent);
sb.AppendLine(value);
}
private static string ToDartType(JToken token)
{
return token.Type switch
{
JTokenType.Integer => "int",
JTokenType.Float => "float",
JTokenType.String => "String",
JTokenType.Boolean => "bool",
JTokenType.Array => $"List<{(token.HasValues ? ToDartType(token.Values().First()) : "dynamic")}>",
_ => "dynamic"
};
}
private static bool IsJsonTypeSupported(JTokenType type)
{
var supportedTokenTypes = new[]
{
JTokenType.Integer,
JTokenType.Float,
JTokenType.String,
JTokenType.Boolean,
};
return supportedTokenTypes.Contains(type);
}
[Obsolete("Seems to skip characters, therefore unreliable.")]
private static string ReadLines()
{
var stringBuilder = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Modifiers == ConsoleModifiers.Alt && key.Key == ConsoleKey.Enter)
break;
if (key.Key == ConsoleKey.Backspace)
{
stringBuilder.Remove(stringBuilder.Length - 1, 1);
Console.CursorLeft--;
continue;
}
stringBuilder.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
return stringBuilder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment