Dart 中的JSON 解析
Dart 中编码,接下JSON,推荐用代码生成器的方式来定义。你需要加注解,然后运行生成器,让dart的编译器为你自动生产代码。
减少你的工作量。
请看示例
import 'package:bsmi_base/bsmi_base.dart' as bb;
import 'package:json_annotation/json_annotation.dart';
//这一行特别重要,它定义了包含 pub 自动生产的 dart代码的 锚点
// 文件名跟这个文件名bsmi_base_example.dart 对应
// 构建的命令为:flutter pub run build_runner build
part 'bsmi_base_example.g.dart';
@JsonSerializable(
anyMap: true,
checked: true,
disallowUnrecognizedKeys: true,
explicitToJson: true,
)
class DemoYml {
@JsonKey(required: true)
final String ym;
DemoYml({required this.ym}) {
if (ym.isEmpty) {
throw ArgumentError.value(ym, 'name', 'Cannot be empty.');
}
}
factory DemoYml.fromJson(Map? json) => _$DemoYmlFromJson(json!);
Map<String, dynamic> toJson() => _$DemoYmlToJson(this);
@override
String toString() => 'DemoYml: ${toJson()}';
}
void main() {
var yt2 = bb.YamlUtils<DemoYml>();
print('yaml: ${yt2.parseYamlFileToClass("example/demo.yml", DemoYml.fromJson)}');
}
我们需要注意,pubspec.yml中要加入相关依赖
dependencies:
yaml: ^3.1.1
checked_yaml: ^2.0.1
json_annotation: ^4.5.0
# path: ^1.8.0
dev_dependencies:
lints: ^2.0.0
test: ^1.16.0
# ···
build_runner: ^2.1.0
build_test: ^2.1.0
json_serializable: ^6.2.0
分类: 默认 标签: 发布于: 2022-06-10 15:52:21, 更新于: 2022-06-10 15:53:23