Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization of nested serializable objects #57

Closed
alexantenna opened this issue Oct 7, 2017 · 6 comments
Closed

Serialization of nested serializable objects #57

alexantenna opened this issue Oct 7, 2017 · 6 comments

Comments

@alexantenna
Copy link

Looks like serializing of annotated object with nested annotated objects via toJson() are not supported or I am completely don't understand how to do it.

Calling method toJson() even for your Person object (which is in your example along with nested Order and Item, code unchanged) fails to include serialized output of nested objects into final output.

Order order1 = new Order()
  ..count = 2
  ..itemNumber = 1
  ..isRushed = true
  ..item = new Item()
  ..itemNumber = 234
  ..isRushed=false;

Person person = new Person('Alexey', 'Kartavenko', new DateTime.now(), orders: <Order>[order1]);
print(person.toJson());

Result:

{firstName: Alexey, lastName: Kartavenko, date-of-birth: 2017-10-07T15:15:11.616592, last-order: null, orders: [Instance of 'Order']}

Looking into generated model code I don't see any attempts to call toJson() method of Order object. Is this by design or am I missing something obvious here?

@alexantenna
Copy link
Author

Ah, I see. I need not to call person.toJson() directly but pass person to JSON.encode().

@madisona
Copy link

FWIW - I did the same thing and spent some time spinning on this. Might be good to show a little more usage in the readme to prevent others from the same issue.

@SaadArdati
Copy link

SaadArdati commented Jun 5, 2020

Ah, I see. I need not to call person.toJson() directly but pass person to JSON.encode().

.... This is so stupid.

@cbatson
Copy link

cbatson commented Dec 18, 2022

Five years going and still a roadbump. Haven't found the trick yet though. @alexantenna where is JSON.encode() located? I see jsonEncode() and json.encode() but not JSON.encode(). Plus, I want a Map, not a String.

It seems the generated fromJson() handles nesting, but not the generated toJson(). I don't understand why the disparity.

@langhoangal
Copy link

JSON.encode().

Stuck for a time on this last year, and this year again :D

@kevmoo
Copy link
Collaborator

kevmoo commented Mar 26, 2023

JSON.encode().

Stuck for a time on this last year, and this year again :D

Just use https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/explicitToJson.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants