🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 映射 映射的方式解析动态的结构更加方便 json ``` const documentJson = ''' { "metadata": { "title": "My Document", "modified": "2023-05-10" }, "blocks": [ { "type": "h1", "text": "Chapter 1" }, { "type": "p", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "type": "checkbox", "checked": false, "text": "Learn Dart 3" } ] } '''; ``` bad ``` // 解析json (String, {DateTime modified}) getMetadata() { if (_json.containsKey('metadata')) { var metadataJson = _json['metadata']; if (metadataJson is Map) { var title = metadataJson['title'] as String; var localModified = DateTime.parse(metadataJson['modified'] as String); return (title, modified: localModified); } } throw const FormatException('Unexpected JSON'); } ``` good ``` (String, {DateTime modified}) getMetadata() { if (_json case { 'metadata': { 'title': String title, 'modified': String localModified, } }) { return (title, modified: DateTime.parse(localModified)); } else { throw const FormatException('Unexpected JSON'); } } ```