【Flutter】JSON String to List
紀錄一下JSON String的解析,包含將JSON String轉為Map或是JSON array String轉為List<Map>,或是直接將JSON String轉為List<Object>。
dart:convert
jsonDecode(jsonString) function
作用|解析字串,回傳JSON object
範例|
- String(JSON) → Map
import 'dart:convert';
const jsonString =
'{"text": "foo", "value": 1, "status": false, "extra": null}';
Map<String, dynamic> data = jsonDecode(jsonString);
print(data['text']); // foo
print(data['value']); // 1
print(data['status']); // false
print(data['extra']); // null
- String(JSON array) → List of Map
import 'dart:convert';
const jsonArray = '''
[{"text": "foo", "value": 1, "status": true},
{"text": "bar", "value": 2, "status": false}]
''';
List<Object> _sidata = <StateMachine>[];
//String to List<Map>
final List<dynamic> dataList = jsonDecode(jsonArray);
print(dataList[0]);
print(dataList[1]);
//List<Map> to List<Object>
for (var item in dataList) {
StateMachine pItem = StateMachine.fromJson(item);
_sidata.add(pItem);
}
final item = dataList[0];
print(item['text']);
print(item['value']);
print(item['status']);
上面這個範例中,同時也要在StateMachine這個Class中新增一個「fromJson()」的function,例如:
factory StateMachine.fromJson(dynamic json) {
return StateMachine(json['text'] as String, json['value'] as String, json['status'] as int);
}
而上面也可以簡化為以下的寫法
import 'dart:convert';
const jsonArray = '''
[{"text": "foo", "value": 1, "status": true},
{"text": "bar", "value": 2, "status": false}]
''';
//String to List<Object>
var _sidata = jsonArray.map((x) => StateMachine.fromJson(x)).toList();