Flutter 中使用 json_serializable 解析 JSON 并支持泛型

作者:半吊子全栈工匠2024.02.16 23:48浏览量:10

简介:在 Flutter 中,使用 json_serializable 插件可以方便地解析 JSON 数据。通过使用泛型,我们可以使代码更具可重用性和灵活性。本文将介绍如何在 Flutter 中使用 json_serializable 解析 JSON 并支持泛型。

在 Flutter 中,我们经常需要处理 JSON 数据。为了方便地解析 JSON,可以使用 json_serializable 插件。这个插件可以根据 Dart 的类型系统自动生成用于序列化和反序列化 JSON 的代码。

要使用 json_serializable,首先需要将其添加到项目的 pubspec.yaml 文件中:

  1. dependencies:
  2. json_serializable: ^latest_version

然后运行 flutter pub get 命令来安装依赖。

接下来,我们需要定义一个 Dart 类来表示 JSON 数据。这个类应该使用 @JsonSerializable 装饰器标记,并使用泛型参数指定 JSON 数据的类型。例如,假设我们要解析一个包含整数和字符串的 JSON 对象,可以定义一个 Response 类如下:

  1. import 'package:json_annotation/json_annotation.dart';
  2. part 'response.g.dart';
  3. @JsonSerializable()
  4. class Response<T> {
  5. final int code;
  6. final T data;
  7. Response(this.code, this.data);
  8. factory Response.fromJson(Map<String, dynamic> json) => _$ResponseFromJson<T>(json);
  9. }

在这个例子中,Response 类有两个成员变量:codedatacode 是整数类型,而 data 是泛型参数 T 表示的类型。我们使用了 @JsonSerializable() 装饰器来标记这个类,并使用 part 'response.g.dart' 来指定生成的代码文件名。

接下来,我们需要运行 dartdevc -t lib/response.dart 命令来生成代码文件 response.g.dart。这个文件将包含用于序列化和反序列化 Response 类的代码。

现在我们可以使用 Response 类来解析 JSON 数据了。例如:

```dart
import ‘package:flutter/material.dart’;
import ‘package:http/http.dart’ as http;
import ‘response.dart’;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: ‘Flutter App’,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
final String url = ‘https://api.example.com/data‘; // 替换为实际的 API 地址
Response response;

Future fetchData() async {
final response = await http.get(url);
final jsonResponse = jsonDecode(response.body);
this.setState(() {
this.response = Response.fromJson(jsonResponse);
});
}