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

相关推荐
0wioiw011 小时前
Flutter基础()
flutter
bing_15811 小时前
Spring MVC 根据请求头 (如 Accept) 怎么返回 JSON 或 XML 数据?
spring·json·mvc
肥肥呀呀呀14 小时前
flutter 视频通话flutter_webrtc
flutter
明似水16 小时前
2025年Flutter项目管理技能要求
flutter
半路_出家ren16 小时前
python处理异常,JSON
python·json·异常处理
肥肥呀呀呀18 小时前
flutter使用命令生成BinarySize分析图
flutter
程序猿阿伟18 小时前
《数字分身进化论:React Native与Flutter如何打造沉浸式虚拟形象编辑》
flutter·react native·react.js
怀君18 小时前
Flutter——数据库Drift开发详细教程(六)
数据库·flutter
傻小胖1 天前
json-server的用法-基于 RESTful API 的本地 mock 服务
后端·json·restful
search71 天前
配置文件介绍xml、json
xml·json