A .NET 11 class library and Blazor Server sample web page for generating null-safe Dart model classes from JSON.
Tools.Coding.Json2Dart: framework-only class library; no external runtime dependencies.Tools.Coding.WebPage: Blazor Server UI with a Prism-highlighted JSON editor.tests/Tools.Coding.Json2Dart.Tests: generator tests.
using Tools.Coding.Json2Dart.Generation;
var generator = new JsonToDartGenerator();
var pureDart = generator.Generate(json, new GenerationOptions
{
RootClassName = "ApiResponse",
Mode = DartGenerationMode.Pure,
IndentSize = 2
});
var jsonSerializable = generator.Generate(json, new GenerationOptions
{
RootClassName = "ApiResponse",
Mode = DartGenerationMode.JsonSerializable
});Pure generates fromJson and toJson without package dependencies. JsonSerializable generates @JsonSerializable, @JsonKey where a Dart field name differs from its JSON key, and a part '<root_file>.g.dart' declaration. The consuming Dart project needs json_annotation and build_runner/json_serializable as development dependencies.
The root JSON value must be an object. Nested objects and arrays of objects are recursively emitted as model classes. Fields absent from some object samples, and fields containing explicit null, are made nullable. Integer/decimal mixtures are inferred as double. Incompatible mixed values fall back to dynamic rather than generating an invalid type. Existing camelCase names are preserved (for example, userId stays userId, and accObserved stays accObserved); only the first character is lowercased when needed. Snake_case and kebab-case names are converted to lowerCamelCase (for example, acc_on becomes accOn), while the original JSON key is retained for serialization.
The web page includes a JSON editor with syntax highlighting, line numbers, validation, formatting, minification, Tab indentation and clipboard support. The editor's text is read through a small JS interop API; JSON parsing and Dart source generation remain in the class library.
Requires the .NET 11 SDK.
dotnet build Tools.Coding.Json2Dart/Tools.Coding.Json2Dart.csproj
dotnet build Tools.Coding.WebPage/Tools.Coding.WebPage.csproj
dotnet test tests/Tools.Coding.Json2Dart.Tests/Tools.Coding.Json2Dart.Tests.csprojFor generated-code acceptance, run dart format and dart analyze against the generated .dart file in a Dart SDK environment. The current execution environment used to prepare this source archive did not include the .NET or Dart SDK, so those build/analyzer checks remain to be run on a development machine.