json_serializable.dart
json_serializable.dart copied to clipboard
JsonKey.readValue having an error when trying to serialize complex objects
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
What a shame, hanging here a year
@nzackoya – pull requests are welcome. I maintain this package in my free time.
is there any workaround solution? without needing to flat all props?