Articles

How to Generate C#, Python, and Dart Classes from JSON Samples

Infer nested models, collections, nullable fields, and JSON mappings from a representative sample without confusing generated code with a complete API contract.

Published on Updated on 7 min read

Published by TOOLFINASources and tool behavior checked on the updated date.

Generated models begin with evidence, not certainty

A JSON response is data, not a type declaration. It shows the values present in one payload at one moment, while a C#, Python, or Dart model must describe every value the application expects to receive. A sample containing `42` can support an integer field, and a sample containing `4.8` can support a floating-point field, but neither says whether the service might later return null, omit the field, or send a larger number. Likewise, a date-looking string is still a JSON string until the API contract gives it stronger meaning. Useful generation therefore starts with conservative evidence and leaves semantic decisions visible for review.

The target language changes how that evidence should be expressed. C# commonly uses PascalCase properties and `System.Text.Json` attributes to preserve original keys. Python dataclasses use annotated fields, but type hints are guidance for tools rather than runtime validation, so explicit `from_dict` and `to_dict` methods make the mapping behavior visible without an extra package. Dart uses UpperCamelCase types, lowerCamelCase fields, sound nullable types, and small `fromJson` and `toJson` methods for manual serialization. A generator should follow each ecosystem instead of producing the same renamed template three times.

JSON to C#, Python & Dart Class Generator: method and assumptions

Parse the sample as strict JSON, then classify each value as null, boolean, integer, general number, string, object, or array. Walk objects recursively and derive nested type names from their keys. For an array of objects, compare every supplied element rather than trusting only the first: merge fields with the same key, promote integer plus decimal observations to a general numeric type, and mark a field nullable when it is null or absent from another element. Homogeneous arrays retain their item type; incompatible mixtures and empty arrays fall back to a language-native unknown type. Finally, sanitize identifiers, resolve collisions, preserve original JSON keys in mapping code, and emit a root wrapper or alias when the payload begins with an array.

ECMA-404 defines JSON syntax but deliberately does not prescribe how values map into a programming language, which is why sample-to-class conversion must state its inference policy. Microsoft documents that `JsonPropertyName` controls the JSON property used in both serialization directions. Python documents that dataclasses derive generated methods from annotated fields while type annotations are not enforced by the runtime. Flutter's serialization guidance shows manual `fromJson` and `toJson` model methods for small projects and recommends generated serialization for larger systems. Effective Dart supplies the UpperCamelCase and lowerCamelCase naming conventions used in the Dart output.

JSON to C#, Python & Dart Class Generator example you can verify

Consider two array elements: `[{"id":1,"name":"A"},{"id":2,"score":4.5}]`. Both observations support a required integer `id`. Because `name` is missing from the second object, its generated type must allow absence; `score` is likewise optional because it appears only in the second object. The array item becomes one merged model rather than two unrelated classes. In C# that can produce nullable `string?` and `double?` properties, in Python fields with `| None = None`, and in Dart nullable `String?` and `double?` fields. The original keys remain stable even when generated field names follow different casing conventions.

A practical merge rule is `observed field type = union of compatible sample observations + absence`. Null contributes nullability rather than replacing a known type. Integer combined with decimal becomes a general number. An object combined with another object merges their keyed fields recursively. An array combines item observations using the same rule. Incompatible shapes such as a number and an object become `object`, `Any`, or `dynamic` depending on the target. This is intentionally less ambitious than guessing enums, dates, UUIDs, money, or domain identifiers from string contents because those guesses require contract knowledge outside JSON syntax.

Where JSON to C#, Python & Dart Class Generator needs extra care

Empty arrays provide no item evidence, and a field observed only as null provides no concrete value type. Duplicate JSON keys are another trap: ordinary JSON parsers retain only the last occurrence, so the generator cannot warn about values already overwritten during parsing. Very large integers may also exceed the exact numeric range of the browser before a target type is selected. Keys containing spaces, punctuation, reserved words, digits, or non-Latin text need valid generated identifiers plus an explicit mapping back to the source key. Deeply nested or extremely wide payloads should be reduced to representative fixtures to keep generation responsive. Most importantly, successful code generation does not prove that the model compiles under every project language version or matches undocumented server behavior.

Compile or analyze the generated file, test deserialization and serialization with more than one real payload, and compare optional fields against API documentation or a schema. Watch for one recurring error: treating a single successful response as the complete contract, especially when later responses may omit fields, return null, mix numeric shapes, or add new object variants.

Checks before keeping the result

  • One valid JSON object or array up to one million characters, a root type name, a target language, an optional domain or namespace, and an optional JSON-mapping choice.
  • Compile or analyze the generated file, test deserialization and serialization with more than one real payload, and compare optional fields against API documentation or a schema.
  • Sample-based inference cannot discover undocumented variants, distinguish every semantic string type, recover precision already lost by JSON number parsing, or replace a maintained JSON Schema or OpenAPI contract.
  • Keep the source payload, root type name, target language, generator settings, and a test fixture beside accepted generated code so later API changes can be reviewed.
  • Format and validate the source JSON first, inspect Base64 fields separately, and regenerate only after comparing the new payload with existing production fixtures.

Sources for JSON to C#, Python & Dart Class Generator

  • ECMA-404: The JSON data interchange syntax

    Ecma International

    Defines the JSON syntax used to decide whether a document is structurally valid JSON.

  • How to customize property names with System.Text.Json

    Microsoft Learn

    Documents how JsonPropertyName preserves an exact JSON key during both serialization and deserialization in C#.

  • Python data classes

    Python Documentation

    Explains how the dataclass decorator derives constructors and other methods from annotated class fields.

  • Support for type hints

    Python Documentation

    Clarifies that Python type annotations support checkers and editors but are not enforced by the runtime itself.

  • JSON and serialization

    Flutter Documentation

    Shows dependency-free Dart model classes with fromJson and toJson methods and explains when larger projects need a maintained generator workflow.

  • Effective Dart: Style

    Dart Documentation

    Defines UpperCamelCase for Dart types and lowerCamelCase for fields and other identifiers.

Use TOOLFINA JSON to C#, Python & Dart Class Generator

Open the TOOLFINA JSON to Class Generator and paste a valid object or array, or load a local `.json` file. Enter a descriptive root name, select C#, Python, or Dart, and enable JSON mapping code when the models must deserialize the original keys. The domain field is optional: it becomes a C# namespace and folder hierarchy, or a snake_case Python/Dart package folder. Generate the code, expand the workspace when you need more room, and review nullability, unknown values, nested names, and collections. Copy or download the combined preview, or download the ZIP when you need one file per generated class. Then run your project compiler, analyzer, formatter, and tests.

Input: one strict JSON object or array up to one million characters, a root type name, and an optional domain, with bounded depth and property/type counts for browser safety. Output: a combined code preview plus an optional ZIP containing one file per generated type, using PascalCase `.cs` filenames or snake_case `.py` and `.dart` filenames. C# uses platform `System.Text.Json`; Python uses standard-library `dataclasses` and `typing`; Dart uses manual map conversion. The tool does not fetch a URL, execute JSON, validate against a schema, or guarantee that one sample covers the production API.

The JSON sample is parsed and converted locally in the browser and is never uploaded, stored, or executed by TOOLFINA. The browser parses strict JSON, walks nested values, merges object samples found in arrays, widens compatible numeric types, marks null or missing fields, and emits language-specific identifiers plus explicit key mappings.

Try this tool

Turn a JSON object or array into typed C#, Python, or Dart models with nested classes, nullability, JSON mappings, and separate-file exports.

JSON to C#, Python & Dart Class Generator

Related tools