json_shield 0.1.1
json_shield: ^0.1.1 copied to clipboard
Dependency-free JSON decoding guard for fromJson-style models. Shape checks, typed exceptions with cause and trace, full-traversal list decoding with aggregated failures, redacted-by-default payloads.
example/json_shield_example.dart
// dart run example/json_shield_example.dart
import 'package:json_shield/json_shield.dart';
// A quicktype-style model, used unmodified.
class User {
final String name;
final int age;
const User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) => User(
name: json['name'] as String,
age: json['age'] as int,
);
}
void main() {
guard.verbose = true; // attach raw payloads while developing
// 1. Single object.
final user = guard.decode(
User.fromJson,
{'name': 'Ada', 'age': 36},
context: 'users_me_get',
);
print('decoded: ${user.name}');
// 2. Broken contract: `name` is an int -> DecodeException with the
// endpoint label, expectation, raw payload, TypeError cause and trace.
try {
guard.decode(User.fromJson, {'name': 123, 'age': 1},
context: 'users_me_get');
} on DecodeException catch (e) {
print(e);
}
// 3. List: full traversal, every failure reported at once.
try {
guard.decodeList(
User.fromJson,
[
{'name': 'a', 'age': 1},
'garbage',
{'name': 'b', 'age': 'NaN'},
],
context: 'users_list',
);
} on DecodeListException catch (e) {
print(e); // 2/3 failed. #1: ...; #2: ...
for (final f in e.errors) {
print(' index ${f.index}: ${f.error.cause}');
}
}
}