當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Dart jsonDecode用法及代碼示例

dart:convert 庫中jsonDecode 函數的用法介紹如下。

用法:

dynamic jsonDecode(
   String source,    
   {Object? reviver(
   Object? key,    
   Object? value   
)?}   
)

解析字符串並返回生成的 Json 對象。

對於解碼期間已解析的每個對象或列表屬性,都會調用一次可選的reviver 函數。 key 參數是列表屬性的整數列表索引、對象屬性的字符串映射鍵或最終結果的 null

默認的reviver(未提供時)是標識函數。

json.decode 的簡寫。如果局部變量隱藏全局 json 常量,則很有用。

例子:

const jsonString =
    '{"text": "foo", "value": 1, "status": false, "extra": null}';

final data = jsonDecode(jsonString);
print(data['text']); // foo
print(data['value']); // 1
print(data['status']); // false
print(data['extra']); // null

const jsonArray = '''
  [{"text": "foo", "value": 1, "status": true},
   {"text": "bar", "value": 2, "status": false}]
''';

final List<dynamic> dataList = jsonDecode(jsonArray);
print(dataList[0]); // {text: foo, value: 1, status: true}
print(dataList[1]); // {text: bar, value: 2, status: false}

final item = dataList[0];
print(item['text']); // foo
print(item['value']); // 1
print(item['status']); // false

相關用法


注:本文由純淨天空篩選整理自dart.dev大神的英文原創作品 jsonDecode function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。