插件介绍

JSON Example 是一个展示三种不同 JSON 反序列化方法的 Flutter 示例应用,旨在帮助开发者选择适合自己项目的 JSON 解析库。该插件支持在鸿蒙(HarmonyOS)平台上运行,提供了以下核心功能:

  • 展示三种主流 JSON 解析库的使用方法:dart:convert(内置库)、json_serializable(代码生成)和 built_value(不可变数据模型)
  • 提供简单对象、嵌套对象、原始值列表和映射的解析示例
  • 帮助开发者理解不同解析库的优缺点和适用场景

如何使用插件

1. 包的引入

由于这是一个自定义修改版本,需要以 Git 形式引入。在引用的项目中,编辑 pubspec.yaml 文件,添加以下依赖配置:

dependencies:
  json_annotation:
    git:
      url: "https://atomgit.com/"
      path: "packages/json_annotation/json_annotation"
  built_collection:
    git:
      url: "https://atomgit.com/"
      path: "packages/built_collection/built_collection"
  built_value:
    git:
      url: "https://atomgit.com/"
      path: "packages/built_value/built_value"

  # 开发依赖
dev_dependencies:
  build_runner:
    git:
      url: "https://atomgit.com/"
      path: "packages/build_runner/build_runner"
  built_value_generator:
    git:
      url: "https://atomgit.com/"
      path: "packages/built_value_generator/built_value_generator"
  json_serializable:
    git:
      url: "https://atomgit.com/"
      path: "packages/json_serializable/json_serializable"

添加依赖后,运行以下命令获取依赖包:

flutter pub get

2. 三种 JSON 解析库的 API 调用

2.1 使用 dart:convert

dart:convert 是 Dart 内置的 JSON 解析库,使用手动方式实现序列化和反序列化:

// 导入必要的库
import 'dart:convert';

// 定义数据模型
class SimpleObject {
  const SimpleObject({
    this.aString,
    this.anInt,
    this.aDouble,
    this.aListOfStrings,
    this.aListOfInts,
    this.aListOfDoubles,
  });

  final String? aString;
  final int? anInt;
  final double? aDouble;
  final List<String>? aListOfStrings;
  final List<int>? aListOfInts;
  final List<double>? aListOfDoubles;

  // 手动实现 fromJson 方法
  factory SimpleObject.fromJson(Map<String, dynamic> json) {
    return SimpleObject(
      aString: json['aString'] as String?,
      anInt: json['anInt'] as int?,
      aDouble: json['aDouble'] as double?,
      aListOfStrings: json['aListOfStrings'] != null
          ? List<String>.from(json['aListOfStrings'] as Iterable<dynamic>)
          : null,
      aListOfInts: json['aListOfInts'] != null
          ? List<int>.from(json['aListOfInts'] as Iterable<dynamic>)
          : null,
      aListOfDoubles: json['aListOfDoubles'] != null
          ? List<double>.from(json['aListOfDoubles'] as Iterable<dynamic>)
          : null,
    );
  }
}

// 使用示例
String jsonString = '{"aString": "Hello", "anInt": 123}';
Map<String, dynamic> jsonMap = jsonDecode(jsonString);
SimpleObject object = SimpleObject.fromJson(jsonMap);
2.2 使用 json_serializable

json_serializable 使用代码生成方式,减少样板代码:

// 导入必要的库
import 'package:json_annotation/json_annotation.dart';

// 生成的代码文件
part 'serializable_object.g.dart';

// 使用注解标记需要生成代码的类
()
class SerializableObject {
  SerializableObject({
    this.aString,
    this.anInt,
    this.aDouble,
    this.aListOfStrings,
    this.aListOfInts,
    this.aListOfDoubles,
  });

  final String? aString;
  final int? anInt;
  final double? aDouble;
  final List<String>? aListOfStrings;
  final List<int>? aListOfInts;
  final List<double>? aListOfDoubles;

  // 自动生成的 fromJson 和 toJson 方法
  factory SerializableObject.fromJson(Map<String, dynamic> json) =>
      _$SerializableObjectFromJson(json);

  Map<String, dynamic> toJson() => _$SerializableObjectToJson(this);
}

使用前需要运行代码生成命令:

flutter pub run build_runner build

然后可以这样使用:

String jsonString = '{"aString": "Hello", "anInt": 123}';
Map<String, dynamic> jsonMap = jsonDecode(jsonString);
SerializableObject object = SerializableObject.fromJson(jsonMap);
2.3 使用 built_value

built_value 创建不可变数据模型,提供类型安全:

// 导入必要的库
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';

// 生成的代码文件
part 'built_object.g.dart';

// 定义不可变数据模型
abstract class BuiltObject implements Built<BuiltObject, BuiltObjectBuilder> {
  static Serializer<BuiltObject> get serializer => _$builtObjectSerializer;

  String? get aString;
  int? get anInt;
  double? get aDouble;
  BuiltList<String>? get aListOfStrings;
  BuiltList<int>? get aListOfInts;
  BuiltList<double>? get aListOfDoubles;

  BuiltObject._();

  factory BuiltObject([void Function(BuiltObjectBuilder) updates]) = _$BuiltObject;
}

使用前需要运行代码生成命令:

flutter pub run build_runner build

然后可以这样使用:

// 假设已经定义了序列化器
final standardSerializers = (Serializers().toBuilder()
      ..addAll([
        BuiltObject.serializer,
        // 其他序列化器
      ]))
    .build();

String jsonString = '{"aString": "Hello", "anInt": 123}';
BuiltObject object = standardSerializers.deserializeWith(
    BuiltObject.serializer,
    jsonDecode(jsonString),
);

总结

JSON Example 插件提供了三种主流 JSON 解析库的使用示例,帮助开发者根据项目需求选择合适的解析方式:

  • dart:convert:适合简单项目或需要高度自定义解析逻辑的场景
  • json_serializable:适合中大型项目,通过代码生成减少样板代码
  • built_value:适合需要不可变性和类型安全的复杂项目

在鸿蒙平台上使用该插件时,需要通过 Git 形式引入自定义修改版本的依赖包,并根据项目需求选择合适的 JSON 解析库。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐