google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.54k stars 392 forks source link

More descriptive error messages when deserialising #1402

Closed bramp closed 4 months ago

bramp commented 4 months ago

This is a feature request for more descriptive / helpful error messages.

Take this example:

@JsonSerializable
class Person {
  Person({
    required this.name,
  });

  factory Person.fromJson(Map<String, dynamic> json) =>
      _$PersonFromJson(json);

  final String name;
}

and I try and deserialise a empty object (e.g Person.fromJson({})) I get the error:

  type 'Null' is not a subtype of type 'String' in type cast
  person.g.dart 31:24  _$PersonFromJson
  person.dart 21:7     new Person.fromJson

a more helpful error message would be

  Expected field 'name' was null or missing

It doesn't seem possible to configure these errors, or make the error checking more robust. Right now all I can tell my user is Something is wrong with your JSON object.

am I missing something? or is this a reasonable feature request?

thanks

❯ dart --version
Dart SDK version: 3.3.0 (stable) (Tue Feb 13 10:25:19 2024 +0000) on "macos_arm64"
kevmoo commented 4 months ago

Try https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/checked.html

bramp commented 4 months ago

doh, thanks I totally missed that.

In my example, it now generates:

  CheckedFromJsonException
  Could not create `Person`.
  There is a problem with "name".
  type 'Null' is not a subtype of type 'String' in type cast

Still not as descriptive as the field 'name' is missing, but it's certainly better, and I can live with that.