Flutter JSON与Chopper网络请求转换插件json_serializable_chopper_converter的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter JSON与Chopper网络请求转换插件json_serializable_chopper_converter的使用

特性

  • 全面的测试覆盖
  • 轻松集成到Chopper
  • 支持泛型响应

使用方法

final client = ChopperClient(
    services: [
        _$ApiService(),
    ],
    converter: JsonSerializableConverter({
        PostResource: PostResource.fromJson,
    }),
);

其他包

如果您需要其他常用类型的JsonSerializable转换器,可以查看以下这些包:

完整示例代码

以下是一个完整的示例代码,展示了如何使用json_serializable_chopper_converter来处理JSON数据和Chopper网络请求。

// ignore_for_file: avoid_print

import 'package:chopper/chopper.dart';
import 'package:json_serializable_chopper_converter/json_serializable_chopper_converter.dart';
import 'package:json_annotation/json_annotation.dart' hide JsonConverter;

part 'json_serializable_chopper_converter_example.g.dart';
part 'json_serializable_chopper_converter_example.chopper.dart';

abstract class APIModel {
  const APIModel();
  Map<String, dynamic> toJson();
}

[@JsonSerializable](/user/JsonSerializable)(
  genericArgumentFactories: true,
)
class Paginator<T extends APIModel> extends APIModel {
  const Paginator({
    required this.count,
    required this.next,
    required this.previous,
    required this.results,
  });

  final int count;
  final String? next;
  final String? previous;
  final List<T> results;

  // 从JSON数据创建Paginator对象
  factory Paginator.fromJson(Map<String, dynamic> json, JsonFactory jsonFactory) =>
      _$PaginatorFromJson<T>(json, (json) => jsonFactory(json as Map<String, dynamic>) as T);
  
  [@override](/user/override)
  Map<String, dynamic> toJson() => _$PaginatorToJson(this, (T value) => value.toJson());
}

[@JsonSerializable](/user/JsonSerializable)()
class PostResource extends APIModel {
  final int id;
  final String title;
  final String body;
  [@JsonKey](/user/JsonKey)(name: 'user_id')
  final int userId;

  const PostResource({
    required this.id,
    required this.title,
    required this.body,
    required this.userId,
  });

  // 从JSON数据创建PostResource对象
  factory PostResource.fromJson(Map<String, dynamic> json) => _$PostResourceFromJson(json);
  
  [@override](/user/override)
  Map<String, dynamic> toJson() => _$PostResourceToJson(this);
}

[@JsonSerializable](/user/JsonSerializable)()
class PostCreateBody extends APIModel {
  final String title;
  final String body;
  [@JsonKey](/user/JsonKey)(name: 'user_id')
  final int userId;

  const PostCreateBody({
    required this.title,
    required this.body,
    required this.userId,
  });

  // 从JSON数据创建PostCreateBody对象
  factory PostCreateBody.fromJson(Map<String, dynamic> json) => _$PostCreateBodyFromJson(json);
  
  [@override](/user/override)
  Map<String, dynamic> toJson() => _$PostCreateBodyToJson(this);
}

[@ChopperApi](/user/ChopperApi)(baseUrl: 'https://jsonplaceholder.typicode.com')
abstract class ApiService extends ChopperService {
  // 获取所有Post
  [@Get](/user/Get)(path: '/posts')
  Future<Response<List<PostResource>>> list();

  // 获取指定ID的Post
  [@Get](/user/Get)(path: '/posts/{id}')
  Future<Response<PostResource>> retrieve([@Path](/user/Path)('id') int id);

  // 创建一个新的Post
  [@Post](/user/Post)(path: '/posts')
  Future<Response<PostResource>> post(
    @Body() PostCreateBody body,
  );

  // 创建API服务实例
  static ApiService create() {
    final client = ChopperClient(
      services: [
        _$ApiService(),
      ],
      interceptors: const [
        HeadersInterceptor(
          {
            'Cache-Control': 'no-cache',
            'Content-Type': 'application/json; charset=UTF-8',
          },
        ),
      ],
      converter: JsonSerializableConverter({
        PostResource: PostResource.fromJson,
        Paginator<PostResource>: (json) => Paginator<PostResource>.fromJson(json, PostResource.fromJson),
        PostCreateBody: PostCreateBody.fromJson,
      }),
    );

    return _$ApiService(client);
  }
}

void main() async {
  final apiService = ApiService.create();

  // 获取所有Post
  final response = await apiService.list();
  print(response.body!.map((e) => e.toJson()));
}

更多关于Flutter JSON与Chopper网络请求转换插件json_serializable_chopper_converter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON与Chopper网络请求转换插件json_serializable_chopper_converter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用json_serializable_chopper_converter插件来将JSON数据与网络请求结合起来的示例代码。这个示例将展示如何设置Chopper客户端、定义API接口、使用json_serializable生成数据模型,并通过json_serializable_chopper_converter进行JSON转换。

1. 添加依赖

首先,在pubspec.yaml文件中添加必要的依赖:

dependencies:
  flutter:
    sdk: flutter
  chopper: ^4.0.0
  json_annotation: ^4.0.1
  json_serializable_chopper_converter: ^2.0.0 # 请确保版本是最新的

dev_dependencies:
  build_runner: ^2.0.4
  chopper_generator: ^4.0.0
  json_serializable: ^4.0.1

2. 定义数据模型

创建一个数据模型,例如User,并使用json_serializable生成JSON序列化和反序列化代码。

// user_model.dart
import 'package:json_annotation/json_annotation.dart';

part 'user_model.g.dart';

@JsonSerializable()
class User {
  final int id;
  final String name;
  final String email;

  User({required this.id, required this.name, required this.email});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

运行flutter pub run build_runner build来生成user_model.g.dart文件。

3. 定义Chopper API服务

创建一个Chopper API服务接口,并定义所需的方法。

// api_service.dart
import 'package:chopper/chopper.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:json_serializable_chopper_converter/json_serializable_chopper_converter.dart';
import 'user_model.dart';

part 'api_service.chopper.dart';

@ChopperApi(baseUrl: 'https://jsonplaceholder.typicode.com')
abstract class ApiService extends ChopperClient {
  static ApiService create() {
    final client = ChopperClient(
      baseUrl: 'https://jsonplaceholder.typicode.com',
      services: [
        _$ApiService(),
      ],
      converter: JsonSerializableConverter(), // 使用json_serializable_chopper_converter
    );
    return _$ApiServiceImpl(client);
  }

  @Get(path: '/users/{id}')
  Future<Response<User>> getUser(@Path() int id);
}

运行flutter pub run build_runner build来生成api_service.chopper.dart文件。

4. 使用Chopper API服务

在你的Flutter应用中,使用生成的Chopper API服务来发起网络请求。

// main.dart
import 'package:flutter/material.dart';
import 'package:your_app_name/api_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  User? user;
  var _isLoading = false;

  @override
  void initState() {
    super.initState();
    _fetchUser();
  }

  Future<void> _fetchUser() async {
    setState(() {
      _isLoading = true;
    });

    final apiService = ApiService.create();
    final response = await apiService.getUser(1);

    if (response.isSuccess) {
      setState(() {
        user = response.body;
        _isLoading = false;
      });
    } else {
      // Handle error
      print('Error fetching user: ${response.error?.message}');
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Chopper JSON Example'),
        ),
        body: Center(
          child: _isLoading
              ? CircularProgressIndicator()
              : user != null
                  ? Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text('ID: ${user!.id}'),
                        Text('Name: ${user!.name}'),
                        Text('Email: ${user!.email}'),
                      ],
                    )
                  : Text('No user data'),
        ),
      ),
    );
  }
}

总结

以上代码展示了如何在Flutter项目中使用json_serializable_chopper_converter插件来结合JSON数据和网络请求。通过这种方式,你可以轻松地定义数据模型,发起网络请求,并自动处理JSON数据的序列化和反序列化。确保你已经正确添加了所有依赖,并运行了flutter pub run build_runner build命令来生成必要的代码文件。

回到顶部