JSON to Dart
Generate Dart classes from a JSON sample, including a fromJson factory and a toJson method — no build step, no code generation package required. Null safety is respected: required fields use required this.x, optional ones become nullable.
How to generate Dart classes from JSON
- Paste a JSON sample — ideally an array of several records, so optional fields are detected.
- Set the Root type name. Nested objects are named after the key that holds them, singularised for arrays.
- Leave fields final unless you need to mutate the model after construction.
- The generated
fromJsoncasts each value explicitly, so a shape mismatch fails loudly at the boundary rather than deep in your widget tree. - Copy the code, or download it as a file.
Type mapping
- Integers →
int; fractional →double; booleans →bool; strings →String. - Arrays →
List<T>, mapped element by element so nested objects are constructed properly. - Objects → a class with its own
fromJson/toJson. - null / mixed →
dynamic.
Careful with int versus double: a JSON value of 7 decodes as
int in Dart even when the field is sometimes fractional. If a number can be either, change
the type to num, or cast with (json['x'] as num).toDouble().
Getting good types out of a sample
Type inference from a sample is only as good as the sample. Three habits make the output far more useful:
- Paste an array, not one record. When you pass several records, a key missing from any of them is marked optional and a field that is sometimes a number and sometimes a float widens to a float. One record makes everything look required.
- Include the awkward cases. A record with a null, an empty array, and a missing optional key teaches the generator more than ten identical happy-path records.
- Check unions by hand. A field that holds different shapes in different records falls back to the language's "any" type. That is a signal your data has a variant the generator cannot express — model it explicitly.
Privacy
Nothing is uploaded. Inference and code generation run in this tab. No server sees the payload you paste — which matters, because real API responses tend to contain real user data.
FAQ
Should I use json_serializable instead?
For a large app, probably — annotations plus build_runner keep the boilerplate out of your diffs. This output is the right choice for a quick model, a script, or when you want zero build dependencies.
Why does fromJson cast instead of just assigning?
Because json['x'] is dynamic. Without a cast the error surfaces later, somewhere unrelated. An explicit cast fails at the parse boundary with a message that names the field.
Does it generate copyWith or equality?
No — those are opinionated and long. If you want them, freezed generates the whole set from a much shorter declaration.