json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

JsonKey.readValue having an error when trying to serialize complex objects

Open glennfordd opened this issue 3 years ago • 3 comments

Reproducible steps

{
  "id": "123",
  "firstName": "John",
  "lastName": "Doe"
  "age": "27"
}
import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class Person {
  const Person (this.id, this.name, this.age);

  final String id;

  @JsonKey(readValue: _readName)
  final Name name;
  final int age;

  static Name _readName(Map map, String key) => Name (map['firstName'], map['lastName']);
}

class Name {
  const Name (this.firstName, this.lastName);

  final String firstName;
  final String lastName;
}

If you run a build for this class, it will have an error of:

Could not generate `fromJson` code for `name`.
To support the type `Name` you can:
* Use `JsonConverter`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
* Use `JsonKey` fields `fromJson` and `toJson`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html

Environment

Flutter: 2.10.3 json_serializable: 6.1.5 json_annotation: 4.4.0

glennfordd avatar Apr 01 '22 21:04 glennfordd

What a shame, hanging here a year

nzackoya avatar Mar 01 '23 14:03 nzackoya

@nzackoya – pull requests are welcome. I maintain this package in my free time.

kevmoo avatar Mar 01 '23 16:03 kevmoo

is there any workaround solution? without needing to flat all props?

YousefAK009 avatar Mar 26 '24 15:03 YousefAK009