Closed
Description
For example I have json file:
[
{
"name": "test1",
"result": "success"
},
{
"name": "test2",
"result": "fail"
}
]
How can I deserialise it properly?
I understand that possible way to do it is to wrap this list into top-level object with a key. Something like that:
{
"list_of_items": [
{
"name": "test1",
"result": "success"
},
...
]
}
But I have multiple files with such structure so I wonder if there any other ways to handle it?
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
[-]Deserialise top-level list of items[/-][+]How to deserialise top-level list of items[/+]davidmorgan commentedon Jan 9, 2019
You could iterate over the top level list calling
serializers.deserialize
on each inner map. You'll need to useStandardJsonPlugin
to get it to accept the map format instead of the default list format; the third heading here:https://medium.com/dartlang/moving-fast-with-dart-immutable-values-1e717925fafb
votruk commentedon Jan 11, 2019
Thanks for response - the approach you have suggested works well.
In case anybody needs this functionality I leave here code snippet of how to handle this situation (code should be placed in
serializers.dart
file):So if you have json file
And built value class:
You can use method
deserializeListOf
from above as:anqit commentedon May 20, 2022
I have two issues with the above code snippet:
A value of type 'T?' can't be returned from the function 'deserialize' because it has a return type of 'T'
. I can fix this by adding!
:Any thoughts? My guess is later versions of Dart have more stringent type/null checking? Other ways to de/serialize collections of built values?
EDIT:
Adding the following hacky "solution" may work (compiles at least, haven't run the code yet), I'm wondering if there's a more type-safe way to do this still: