Flutter-如何序列化和反序列化为json对象

在Flutter中,使用json_serializable可以帮助你自动地序列化和反序列化JSON数据。这通常通过json_serialization库实现,它基于Dart的源代码生成功能。以下是如何在Flutter中使用json_serializable的步骤:

1.添加依赖:

首先,确保你的pubspec.yaml文件中添加了json_serialization的依赖:

复制代码
dependencies:  
  flutter:  
    sdk: flutter  
  json_annotation: ^x.x.x # 使用最新版本  
  
dev_dependencies:  
  build_runner: ^x.x.x # 使用最新版本  
  json_serializable: ^x.x.x # 使用最新版本

运行flutter pub get以获取依赖。

2.创建数据模式:

创建一个Dart类来表示你的数据模型,并使用json_serializable提供的注解来标记它。

比如有个最简单的商品类GoodsItem,如下:

Dart 复制代码
import 'package:json_annotation/json_annotation.dart';
part 'goods_item.g.dart';

@JsonSerializable()
class GoodsItem {
  @JsonKey(name: 'goods_name')
  String? goodsName;
  @JsonKey(name: 'in_time')
  String? inTime;

  GoodsItem({required this.goodsName, required this.inTime});

  /// 从JSON创建GoodsItem实例的工厂构造函数
  factory GoodsItem.fromJson(Map<String, dynamic> json) =>
      _$GoodsItemFromJson(json);

  /// 将GoodsItem实例转换为JSON的函数

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

  // 实现SuperEntity接口的方法,这里以toString为例,具体实现根据接口定义
  @override
  String toString() {
    return 'GoodsItem{goodsName: $goodsName, inTime: $inTime}';
  }
}

注意:fromJson和toJson方法都是固定写法,具体实现会通过后面的脚本生成,我们只需要在需要序列化的地方使用相应的方法。

3.生成序列化和反序列化代码

在你的项目根目录(包含pubspec.yaml的目录)中运行以下命令:

bash 复制代码
flutter packages pub run build_runner build
复制代码
等待自动化脚本完成,会在你的实体类文件夹中生成序列化和反序列化的代码,比如上面part 'goods_item.g.dart'中的这个xxx.g.dart文件,这个文件就是实现了_$xxxFromJson和_$xxxToJson
4.使用序列化和反序列化

现在,你可以轻松地将User对象序列化为JSON字符串,或将JSON字符串反序列化为User对象。

Dart 复制代码
    //序列化
    GoodsItem goodsItem = GoodsItem(goodsName: "华为P70", inTime: "2024-04-20 12:00:00");
    print(goodsItem .toJson()); //输出一个Map对象  {goods_name: 华为P70, in_time: 2024-04-20 12:00:00}
    print(jsonEncode(goodsItem.toJson())); //输出一个字符串  {"goods_name":"华为P70","in_time":"2024-04-20 12:00:00"}

    //反序列化
    String goodsJson = '{"goods_name":"华为P70","in_time":"2024-04-20 12:00:00"}';
    Map<String, dynamic> goodsMap = jsonDecode(goodsJson);
    GoodsItem goodsItem2 = GoodsItem.fromJson(goodsMap);
    print(goodsItem2 .toJson()); //输出一个Map对象  {goods_name: 华为P70, in_time: 2024-04-20 12:00:00}
    print("goodsName=${goodsItem2.goodsName}"); //输出 goodsName=华为P70

通过这种方法,你可以轻松地处理JSON数据与Flutter对象之间的转换,而无需手动编写大量的序列化和反序列化代码。

相关推荐
TT_Close5 小时前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
TT_Close7 小时前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
恋猫de小郭10 小时前
Flutter 发布官方 Skills ,Flutter 在 AI 领域再添一助力
android·前端·flutter
恋猫de小郭1 天前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
明君879971 天前
Flutter 如何给图片添加多行文字水印
前端·flutter
四眼肥鱼2 天前
flutter 利用flutter_libserialport 实现SQ800 串口通信
前端·flutter
火柴就是我2 天前
让我们实现一个更好看的内部阴影按钮
android·flutter
王晓枫2 天前
flutter接入三方库运行报错:Error running pod install
前端·flutter
shankss3 天前
Flutter 下拉刷新库 pull_to_refresh_plus 设计与实现分析
flutter
忆江南3 天前
iOS 深度解析
flutter·ios