Hi, thanks for the wonderful library! This is like a feature request since there seems no existing supply.
For instance, suppose we have (ignoring unrelated details):
class A { Animal animal; String fieldInA;}
abstract class Animal { String fieldInBaseClass; }
class Dog extends Animal { String name; }
class Human extends Animal { int id; }
Then I want to serialize and de-serialize the "animal" into concrete classes. For instance, the following object:
A a1 = A(animal: Dog(fieldInBaseClass: 'base', name: 'hi'), fieldInA:'a');
A a2= A(animal: Human(fieldInBaseClass: 'base', id: 42), fieldInA:'a');
should be able to be converted back and forth with the following json string:
{fieldInA: 'a', animal: {type: 'Dog', fieldInBaseClass: 'base', name: 'hi'}}
{fieldInA: 'a', animal: {type: 'Human', fieldInBaseClass: 'base', id: 42}}
Thanks very much for any reply!
You could absolutely create factory Animal.fromJson(...) { ... } that inspects the JSON content and forwards to right subclass fromJson.
@kevmoo Thanks! However, it is not automated...?
Doing this in an automated way would be very complex. we are actively
avoiding adding a lot of new complexity to this package just to make sure
maintenance stays consistent.
On Thu, Jan 30, 2020, 15:36 fzyzcjy notifications@github.com wrote:
@kevmoo https://github.com/kevmoo Thanks! However, it is not
automated...?—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/597?email_source=notifications&email_token=AAAEFCTBAVB7PBO5WV73JHTRANQBLA5CNFSM4KNTMUM2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEKM6WAI#issuecomment-580512513,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AAAEFCWN73FBSRK6QUX3Y7DRANQBLANCNFSM4KNTMUMQ
.
Ah fine... So I may implement it by myself. Thanks
@kevmoo My proposal on syntax and implementations are as follows, which I think is too straightforward to be true... Is this fine? Or will I meet some problems?
@Subclasses([Dog, Human])
abstract class Animal {}
List<Type> subclasses = getTheSubclassesAnnotation();
writeDownTheCode('switch(data["type"]) {');
for(var subclass in subclasses) {
writeDownTheCode('case $subclass: return $subclass.fromJson(data['payload']);');
}
writeDownTheCode('}');