Reputation: 23
I am facing a problem in flutter for converting JSON data as List<Map<String, dynamic>>
.
rawJson =
'[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';
This data need to convert as List<Map<String, dynamic>>
The following code is working, but need help top things.
List<Map<String, dynamic>> _items = [
{
'value': '1',
'label': 'Red',
},
{
'value': '2',
'label': 'Green',
},
{
'value': '3',
'label': 'Yellow',
},
];
Upvotes: 2
Views: 3173
Reputation: 268384
You need to cast your json like this:
var rawJson = '[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';
List<Map<String, dynamic>> output = (json.decode(rawJson) as List).cast();
// or
List<Map<String, dynamic>> output = List.from(json.decode(rawJson) as List);
Upvotes: 4
Reputation: 439
This is probably what your are looking for:
var rawJson =
'[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';
var iterableResult = (jsonDecode(rawJson) as List<dynamic>).map((element) =>
{"value": int.parse(element['value']), "label": element['label']});
var listResult = iterableResult.toList();
print(listResult); // prints [{value: 1, label: red}, {value: 2, label: Green}, {value: 3, label: Yellow}]
Upvotes: 0