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

相关推荐
拾光拾趣录12 分钟前
Flutter跨平台、性能优化与安全
前端·flutter
wtsolutions20 分钟前
Excel to JSON API by WTSolution Documentation
json·excel·api·wtsolutions
木叶丸1 天前
AI三大核心概念通俗指南:AIGC、Agent、MCP
人工智能·flutter·架构
火柴就是我1 天前
每日见闻之Container Decoration
android·flutter
面朝大海,春不暖,花不开2 天前
结构化数据格式解析:JSON 与 XML 的技术应用与实践
xml·json
古希腊被code拿捏的神2 天前
【Flutter】面试记录
flutter·面试·职场和发展
nc_kai2 天前
Flutter 之 table_calendar 控件
flutter
0wioiw02 天前
Flutter基础(前端教程⑨-图片)
前端·flutter
Engandend2 天前
Flutter与iOS混合开发交互
flutter·ios·程序员
PythonicCC2 天前
Django核心知识点详解:JSON、AJAX、Cookie、Session与用户认证
ajax·django·json