Did you know?
As of Dart 3.5.0 (master channel), you can preview the experimental JsonCodable
macro.
This macro augments your classes with fromJson
and toJson
methods, and it works in realtime as you edit your code (no code generation is needed).
Example:
// Example showing how to use the JsonCodable macro
import 'package:json/json.dart';
@JsonCodable()
class Movie {
final int id;
final String title;
}
void main() {
const movieJson = {
'id': 5,
'title': 'Dune',
};
final movie = Movie.fromJson(movieJson);
print(movie.toJson());
}
Note that as of May 2024, JsonCodable
is not configurable and has two big limitations:
- field names must exactly match the keys in the maps
- default values are not supported
If you want to have a play with it, read the official docs for how to enable it:
Happy coding!