How to convert json empty array in Flutter?
At first, you just check your data is empty or not empty then assign the value to your map.
Map<String, dynamic> result;
if(json["data"]!=null && json["data"].isNotEmpty){
result = json["data"];
}
Chen Li Yong
Currently, I'm a mainly mobile programmer (iOS, swift / obj-C) which currently lead and work in multiple projects.
Updated on January 02, 2023Comments
-
Chen Li Yong over 1 year
EDIT: after I check again, as this is a field within an object within a list, turns out somewhere in the list, one object does actually having
"data": {}
Closed question. Thanks for helping.
I have a json field with contents of empty array:
{ "data": [ ] }
The problem is when I tried to put it into a list, it throws a fit.
List<dynamic> result = json["data"]; type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
When I see it's "internal linked hash map", I thought then maybe I can use a Map. So I changed the receiver type as Map.
Map<String, dynamic> result = json["data"]; type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
Why is this happening?
The only way I can finally resolve this is by creating a type-inferred variable as an intermediate:
var temp = json["data"]; print("temp's runtime type: ${temp.runtimeType}"); // List<dynamic> List<dynamic> result = temp; // works
I know this is resolved using workaround for now, but I just want to know why the attempt above is error, and how can I straightly assign the json field content into explicitly-typed variable.
-
pskink over 2 years
final jsonString = '{"data": []}'; final jsonDecoded = json.decode(jsonString); final List<dynamic> data = jsonDecoded['data']; print(data.runtimeType); print(data);
-
Chen Li Yong over 2 years@pskink nvm, after I check again, as this is a field within an object within a list, turns out somewhere in the list, one object does actually having
"data": {}
.
-
-
Chen Li Yong over 2 yearsI see. Then that means it's not considered good practice to assign empty Json field data into Dart variable. Thanks!
-
Jahidul Islam over 2 yearsbut you will get the empty JSON, when JSON is empty it returns a dynamic list. So it would be good to check first
-
Chen Li Yong over 2 yearsAfter some investigation, turns out Dart code is right. As the "data" was a field in an object, within a list of objects, turns out one object does have a
"data": { }
.