/// `dart:convert` 基础:`jsonEncode` / `jsonDecode` 到底产出什么类型。 /// /// JSON 只有 6 种值:object、array、string、number、boolean、null。 /// Dart 把它们映射成:`Map`、`List`、`String`、`num`(int/double)、`bool`、`null`。 /// /// 对照 Go:`json.Unmarshal` 到 `map[string]any` 时数字统一是 `float64`(要用 /// `json.Number` 或 struct 才拿到 int); /// 对照 C:cJSON 用自己的 `cJSON` 结构体树,取值要 `cJSON_GetNumberValue` 并强转。 library; import 'dart:convert'; /// 编码:任何"可 JSON 化"的 Dart 值 → 字符串。 String encodeJson(Object? value) => jsonEncode(value); /// 编码成"带缩进"的字符串,调试/日志用。 String encodePretty(Object? value) => const JsonEncoder.withIndent(' ').convert(value); /// 解码:字符串 → Dart 值(注意返回类型是 `Object?`)。 Object? decodeJson(String raw) => jsonDecode(raw); /// 解码后各部分的真实类型——用来说明"JSON 是弱类型,Dart 是强类型"。 Map decodedTypes(String raw) { final Object? value = jsonDecode(raw); if (value is! Map) return {'root': value.runtimeType.toString()}; return { for (final MapEntry entry in value.entries) entry.key: entry.value.runtimeType.toString(), }; } /// 数值的坑:JSON 只有 "number",Dart 解码时按"有没有小数点"分成 int / double。 /// /// `1` → int,`1.0` → double,`1e3` → double。Go 解码到 `any` 时**全是 float64**, /// 所以 Go 程序员常以为 "JSON 数字就是 float",在 Dart 里会被 int/double 的区分绊住。 ({Object? asInt, Object? asDouble, Object? asExponent}) numberShapes() { return ( asInt: jsonDecode('1'), asDouble: jsonDecode('1.0'), asExponent: jsonDecode('1e3'), ); } /// 不可编码的类型:DateTime / Set / 自定义对象都会抛 `JsonUnsupportedObjectError`。 /// /// Go 的 `encoding/json` 会把 `time.Time` 编码成 RFC3339;Dart 不会替你转换任何类型。 bool canEncode(Object? value) { try { jsonEncode(value); return true; } on JsonUnsupportedObjectError { return false; } }