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
darttest/json_test.dart275 行 · 10 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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';
import 'package:test/test.dart';
void main() {
group('dart:convert 基础', () {
test('JSON 值映射成 Dart 类型', () {
final Object? value = decodeJson('{"s":"x","i":1,"d":1.5,"b":true,"n":null,"l":[1]}');
expect(value, isA<Map<String, Object?>>());
final Map<String, Object?> map = value! as Map<String, Object?>;
expect(map['s'], isA<String>());
expect(map['i'], isA<int>());
expect(map['d'], isA<double>());
expect(map['b'], isA<bool>());
expect(map['n'], isNull);
expect(map['l'], isA<List<Object?>>());
});
test('数字形状:整数字面量 → int,小数/指数 → double', () {
final ({Object? asDouble, Object? asExponent, Object? asInt}) shapes = numberShapes();
expect(shapes.asInt, 1);
expect(shapes.asInt, isA<int>());
expect(shapes.asDouble, 1.0);
expect(shapes.asDouble, isA<double>());
expect(shapes.asExponent, 1000.0);
expect(shapes.asExponent, isA<double>());
});
test('编码不可 JSON 化的类型会抛 JsonUnsupportedObjectError', () {
expect(canEncode(<String, Object?>{'ok': 1}), isTrue);
expect(canEncode(<String, Object?>{'t': DateTime(2024)}), isFalse);
expect(canEncode(<String, Object?>{'s': <int>{1, 2}}), isFalse);
expect(() => encodeJson(DateTime(2024)), throwsA(isA<JsonUnsupportedObjectError>()));
});
test('美化编码与紧凑编码语义一致', () {
const Map<String, Object?> value = <String, Object?>{'a': <int>[1, 2], 'b': <String, String>{'c': 'd'}};
expect(encodePretty(value), contains('\n'));
expect(decodeJson(encodePretty(value)), decodeJson(encodeJson(value)));
});
test('UTF-8 与转义:中文原样保留,控制字符被转义', () {
expect(encodeJson(<String, String>{'k': '中文'}), '{"k":"中文"}');
expect(encodeJson('a\nb'), '"a\\nb"');
expect(decodeJson('"\\u4e2d"'), '中');
});
});
group('手写模型', () {
const String json = '''
{
"id": "u-1",
"email": "ada@example.com",
"name": "Ada",
"tier": "pro",
"tags": ["math", 42, "computing"],
"address": {"city": "London", "zip": "W1"},
"created_at": "1815-12-10T00:00:00Z",
"unknown": "ignored"
}
''';
test('fromJson 处理嵌套、可空、枚举、过滤错误类型的列表元素', () {
final User user = User.fromJson(jsonDecode(json) as Map<String, Object?>);
expect(user.id, 'u-1');
expect(user.name, 'Ada');
expect(user.tier, Tier.pro);
expect(user.tags, <String>['math', 'computing']); // 42 被过滤
expect(user.address?.city, 'London');
expect(user.address?.street, isNull);
expect(user.createdAt, DateTime.utc(1815, 12, 10));
});
test('toJson / fromJson 往返', () {
final User user = User.fromJson(jsonDecode(json) as Map<String, Object?>);
final User again = User.fromJson(decodeJson(encodeJson(user.toJson()))! as Map<String, Object?>);
expect(again.id, user.id);
expect(again.tags, user.tags);
expect(again.tier, user.tier);
expect(again.address, user.address); // Address 重写了 ==
expect(again.createdAt, user.createdAt);
});
test('缺省字段与未知枚举值', () {
final User user = User.fromJson(<String, Object?>{'id': 'x', 'email': 'x@y'});
expect(user.tier, Tier.free); // 缺 tier → free
expect(user.tags, isEmpty);
expect(user.address, isNull);
expect(user.createdAt, isNull);
expect(user.displayName, 'x'); // name 缺失 → 用邮箱前缀
final User unknownTier = User.fromJson(<String, Object?>{
'id': 'x',
'email': 'x@y',
'tier': 'platinum',
});
expect(unknownTier.tier, Tier.free); // 未知值降级
});
test('必需字段缺失时抛 TypeError', () {
expect(() => User.fromJson(<String, Object?>{'email': 'a@b'}), throwsA(isA<TypeError>()));
});
test('订单:列表嵌套与计算值', () {
final Order order = Order.fromJson(<String, Object?>{
'id': 'o-1',
'items': <Object?>[
<String, Object?>{'sku': 'a', 'quantity': 2, 'unit_cents': 150},
'not-an-object',
<String, Object?>{'sku': 'b', 'quantity': 1, 'unit_cents': 500},
],
});
expect(order.items, hasLength(2)); // 非法元素被跳过
expect(order.totalCents, 800);
expect(Order.fromJson(order.toJson()).totalCents, 800);
});
});
group('json_serializable 生成模型', () {
const String json = '''
{
"id": "a-1",
"email": "grace@example.com",
"display_name": "Grace",
"balance_cents": 1200,
"tags": ["navy"],
"address": {"city": "NYC", "zip": "10001"},
"tier": "pro",
"created_at": "2024-05-01T08:30:00Z",
"is_active": false
}
''';
test('snake_case 映射、显式重命名、默认值', () {
final Account a = Account.fromJson(jsonDecode(json) as Map<String, Object?>);
expect(a.displayName, 'Grace');
expect(a.balanceCents, 1200);
expect(a.tier, Tier.pro);
expect(a.createdAt, DateTime.utc(2024, 5, 1, 8, 30));
expect(a.isActive, isFalse);
expect(a.address?.city, 'NYC');
expect(a.tags, <String>['navy']);
});
test('缺字段时走 defaultValue', () {
final Account a = Account.fromJson(<String, Object?>{'id': 'x', 'email': 'x@y'});
expect(a.balanceCents, 0);
expect(a.isActive, isTrue);
expect(a.tier, Tier.free);
expect(a.tags, isEmpty);
expect(a.address, isNull);
});
test('未知枚举值降级为 free 而不是抛异常', () {
final Account a = Account.fromJson(<String, Object?>{
'id': 'x',
'email': 'x@y',
'tier': 'enterprise',
});
expect(a.tier, Tier.free);
});
test('toJson 里的嵌套 Address 已被序列化(可 jsonEncode)', () {
final Account a = Account.fromJson(jsonDecode(json) as Map<String, Object?>);
final Map<String, Object?> out = a.toJson();
expect(out['address'], isA<Map<String, Object?>>());
expect(() => encodeJson(out), returnsNormally);
expect(decodeJson(encodeJson(out))! as Map<String, Object?>, containsPair('display_name', 'Grace'));
});
test('includeFromJson/includeToJson: false 的字段不参与序列化', () {
final Account a = Account.fromJson(<String, Object?>{
'id': 'x',
'email': 'x@y',
'local_only': '不应被读入',
});
expect(a.localOnly, ''); // 输入里的 local_only 被忽略
final Account withLocal = Account(id: 'x', email: 'x@y', localOnly: '仅本机');
final Map<String, Object?> out = withLocal.toJson();
expect(out.containsKey('localOnly'), isFalse);
expect(out.containsKey('local_only'), isFalse);
expect(encodeJson(out), isNot(contains('仅本机')));
});
test('explicitToJson:Payload 递归序列化', () {
final Account a = Account.fromJson(<String, Object?>{'id': 'x', 'email': 'x@y'});
final Payload p = Payload(account: a, extra: <String, Object?>{'trace': 't-1'});
final Map<String, Object?> out = p.toJson();
expect(out['account'], isA<Map<String, Object?>>());
expect(out['extra'], <String, Object?>{'trace': 't-1'});
expect(() => encodeJson(out), returnsNormally);
});
});
group('健壮解码', () {
test('语法错误:FormatException 被包装成 JsonParseException', () {
expect(
() => decodeModel('{"id": "u-1",}', User.fromJson),
throwsA(isA<JsonParseException>().having((JsonParseException e) => e.message, 'message', contains('语法'))),
);
});
test('顶层类型错误', () {
expect(() => decodeModel('[]', User.fromJson), throwsA(isA<JsonParseException>()));
});
test('字段类型错误被识别', () {
expect(
() => decodeModel('{"id": 1, "email": "a@b"}', User.fromJson),
throwsA(isA<JsonParseException>()),
);
});
test('路径感知的解析:错误精确到字段与下标', () {
expect(
() => parseOrderStrict(<String, Object?>{
'id': 'o-1',
'items': <Object?>[
<String, Object?>{'sku': 'a', 'quantity': 1, 'unit_cents': 100},
<String, Object?>{'sku': 'b', 'quantity': 1.5, 'unit_cents': 200},
],
}),
throwsA(isA<JsonParseException>()
.having((JsonParseException e) => e.path, 'path', r'$.items[1].quantity')),
);
expect(
() => parseOrderStrict(<String, Object?>{'id': 'o-1', 'items': 'not-a-list'}),
throwsA(isA<JsonParseException>().having((JsonParseException e) => e.path, 'path', r'$.items')),
);
});
test('expectInt 接受整数值的 double,拒绝 1.5', () {
expect(expectInt(3, r'$.x'), 3);
expect(expectInt(3.0, r'$.x'), 3);
expect(() => expectInt(3.5, r'$.x'), throwsA(isA<JsonParseException>()));
expect(() => expectInt('3', r'$.x'), throwsA(isA<JsonParseException>()));
});
test('decodeList 解析数组并标注下标', () {
final List<User> users = decodeList(
'[{"id":"a","email":"a@x"},{"id":"b","email":"b@x"}]',
User.fromJson,
);
expect(users.map((User u) => u.id), <String>['a', 'b']);
expect(
() => decodeList('[{"id":"a","email":"a@x"}, 42]', User.fromJson),
throwsA(isA<JsonParseException>().having((JsonParseException e) => e.path, 'path', r'$[1]')),
);
});
});
group('大 JSON 与 isolate', () {
test('生成、解码、重新编码都不丢行数', () async {
final String raw = buildFixture(2000);
expect(countRows(raw), 2000);
expect(reEncode(raw), isNotEmpty);
expect(await countRowsInIsolate(raw), 2000);
});
test('格式不对时抛 FormatException', () {
expect(() => countRows('{"rows": 1}'), throwsA(isA<FormatException>()));
expect(() => countRows('[]'), throwsA(isA<FormatException>()));
});
});
}
代码构成: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 个用例全绿