codec 0.11.3
codec: ^0.11.3 copied to clipboard
Type-safe, composable JSON codecs for Dart: structured CodecException with $.path on failure. Nested objects, discriminated unions, recursion, multi-version compatibility.
// Minimal runnable example: hand-written type-safe JSON encode/decode with
// Codec.object, throwing FormatException with `$.path` on failure.
//
// Run: dart run example/codec_example.dart
import 'package:codec/codec.dart';
final class UserModel {
const UserModel({required this.name, this.avatar, required this.age});
final String name;
final String? avatar;
final int age;
static final Codec<UserModel> codec = Codec.object<UserModel>(
(b) => UserModel(
name: b.required('name', Codec.string),
avatar: b.optional('avatar', Codec.string),
age: b.optionalOr('age', Codec.integer, 0),
),
encode: (u) => {
'name': u.name,
'avatar': u.avatar,
'age': u.age,
}.omitNulls,
);
factory UserModel.fromJson(Object? json) =>
codec.decode(json, typeHint: 'UserModel');
Object? toJson() => codec.encode(this);
}
void main() {
// Successful decode.
final user = UserModel.fromJson({'name': 'Ada', 'age': 36});
print('decoded: name=${user.name}, age=${user.age}');
// Round-trip encode; omitNulls omits avatar.
print('encoded: ${user.toJson()}');
// Failure carries the exact path.
try {
UserModel.fromJson({'name': 'Bob', 'age': 'not-a-number'});
} on FormatException catch (e) {
print('error: ${e.message}');
}
}