DartCH 12ch12_json
ch12-json
JSON 编解码:dart:convert、json_serializable、健壮错误处理。完整工程共 12 个文件,其中 12 个文本源文件可在下面在线阅读。
12
在线文本文件
1,502
源码行数
dart / yaml / text
语言
19 KB
打包体积
在线阅读源码
左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。
darttextyaml
12 text files · 1,502 lines
dartbin/ch12_json.dart115 行 · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// 第 12 章可运行入口:`dart run`。
import 'dart:convert';
import 'package:ch12_json/src/decoding.dart';
import 'package:ch12_json/src/json_basics.dart';
import 'package:ch12_json/src/models_generated.dart';
import 'package:ch12_json/src/models_manual.dart';
import 'package:ch12_json/src/order_parser.dart';
import 'package:ch12_json/src/perf.dart';
void main() async {
print('--- 1. dart:convert 基础 ---');
const String raw = '''
{
"name": "Ada",
"age": 36,
"score": 99.5,
"active": true,
"tags": ["dart", "ffi"],
"address": null
}
''';
final Object? decoded = decodeJson(raw);
print('解码后的类型: ${decoded.runtimeType}');
print('各字段类型: ${decodedTypes(raw)}');
print('编码回去: ${encodeJson(decoded)}');
print('美化输出:\n${encodePretty(decoded)}');
final shapes = numberShapes();
print('1 → ${shapes.asInt.runtimeType}, 1.0 → ${shapes.asDouble.runtimeType}, '
'1e3 → ${shapes.asExponent.runtimeType}');
print('DateTime 可编码? ${canEncode(DateTime.now())};Set 可编码? ${canEncode(<int>{1})}');
print('\n--- 2. 手写模型 ---');
const String userJson = '''
{
"id": "u-1",
"email": "ada@example.com",
"name": "Ada Lovelace",
"tier": "pro",
"tags": ["math", "computing", 42],
"address": {"city": "London", "zip": "W1"},
"created_at": "1815-12-10T00:00:00Z",
"unknown_field": "会被忽略"
}
''';
final User user = User.fromJson(jsonDecode(userJson) as Map<String, Object?>);
print('displayName=${user.displayName}, tier=${tierToWire(user.tier)}, '
'city=${user.address?.city}, createdAt=${user.createdAt}');
print('toJson: ${user.toJson()}');
print('往返一致? ${encodeJson(user.toJson()) == encodeJson(user.toJson())}');
print('\n--- 3. json_serializable 生成模型 ---');
const String accountJson = '''
{
"id": "a-1",
"email": "grace@example.com",
"display_name": "Grace",
"tags": ["navy"],
"tier": "enterprise",
"created_at": "2024-05-01T08:30:00Z"
}
''';
final Account account = Account.fromJson(jsonDecode(accountJson) as Map<String, Object?>);
print('displayName=${account.displayName}, balance=${account.balanceCents}(默认值), '
'tier=${account.tier}(未知值降级), isActive=${account.isActive}(默认值)');
print('toJson: ${account.toJson()}');
print('jsonEncode 成功? ${encodeJson(account.toJson()).startsWith('{')}');
final Payload payload = Payload(account: account, extra: <String, Object?>{'trace': 'x-1'});
print('Payload.toJson 里 address 已被递归序列化: '
'${payload.toJson()['account'] is Map<String, Object?>}');
print('\n--- 4. 错误处理 ---');
for (final String bad in <String>[
'{"id": "u-1", "email": "a@b",}', // 尾逗号:JSON 不允许
'{"id": 1, "email": "a@b"}', // id 不是字符串
'[]', // 顶层不是 object
]) {
try {
decodeModel(bad, User.fromJson);
} on JsonParseException catch (e) {
print('$e');
}
}
const String badOrder = '''
{"id": "o-1", "items": [
{"sku": "a", "quantity": 1, "unit_cents": 100},
{"sku": "b", "quantity": 1.5, "unit_cents": 200}
]}
''';
try {
parseOrderStrict(jsonDecode(badOrder));
} on JsonParseException catch (e) {
print('$e ← 注意路径精确到数组下标');
}
print('\n--- 5. 性能 ---');
final String big = buildFixture(20000);
print('fixture 大小: ${(big.length / 1024 / 1024).toStringAsFixed(2)} MB');
var sw = Stopwatch()..start();
final int syncCount = countRows(big);
print('同步解码: $syncCount 行, ${sw.elapsedMilliseconds}ms');
sw = Stopwatch()..start();
final int isolateCount = await countRowsInIsolate(big);
print('isolate 解码: $isolateCount 行, ${sw.elapsedMilliseconds}ms(含 spawn 开销)');
sw = Stopwatch()..start();
reEncode(big);
print('解码+重新编码: ${sw.elapsedMilliseconds}ms');
}
代码构成:dart 33 KB · text 15 KB · yaml 471 B
本地运行
zip → 解压 → 执行$cd examples/ch12-json && dart pub get && dart run这个 zip 里有什么
- • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
- • lib / bin / test / native 全部源码与测试
- • pubspec.yaml、锁文件与平台配置文件
- • 已排除 .dart_tool / build / target / ephemeral 等构建产物
已验证
- dart analyze 0 告警、dart test 24 个用例全绿