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对象之间的转换,而无需手动编写大量的序列化和反序列化代码。

相关推荐
fouryears_234179 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
LinXunFeng14 小时前
Flutter - 详情页 TabBar 与模块联动?秒了!
前端·flutter·开源
阅文作家助手开发团队_山神18 小时前
第三章: 解决Android iPad蓝牙键盘联想词UI不跟随光标问题
flutter
阅文作家助手开发团队_山神18 小时前
第四章:Flutter自定义Engine本地依赖与打包流程
前端·flutter
程序员老刘18 小时前
Flutter 3.35 更新要点解析
flutter·ai编程·客户端
阅文作家助手开发团队_山神20 小时前
第一章: Mac Flutter Engine开发准备工作
前端·flutter
EmmaGuo20151 天前
flutter3.7.12版本设置TextField的contextMenuBuilder的文字颜色
前端·flutter
鹏多多.1 天前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架
来来走走1 天前
Flutter开发 网络请求
android·flutter
SoaringHeart2 天前
Flutter进阶:高内存任务的动态并发执行完美实现
前端·flutter