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

相关推荐
ljh5746491191 小时前
mysql 必须在逗号分隔字符串和JSON字段之间二选一,怎么选
数据库·mysql·json
吴Wu涛涛涛涛涛Tao2 小时前
Flutter 实现「可拖拽评论面板 + 回复输入框 + @高亮」的完整方案
android·flutter·ios
小孔龙2 小时前
02.Kotlin Serialization 属性序列化控制
kotlin·json
Cachel wood5 小时前
信息检索、推荐系统模型排序质量指标:AP@K和MAP@K
windows·搜索引擎·json·推荐系统·搜索
tebukaopu14812 小时前
json文件转excel
json·excel
星秋Eliot1 天前
Flutter多线程
flutter·async/await·isolate·flutter 多线程
农夫三拳_有点甜1 天前
Flutter Assets & Media
flutter
小孔龙1 天前
01.Kotlin Serialization - 基础用法
kotlin·json
佛珠散了一地1 天前
【qt】通过TCP传输json,json里包含图像
qt·tcp/ip·json