美文网首页
flutter入门到放弃5

flutter入门到放弃5

作者: xiaotimel | 来源:发表于2023-11-23 11:41 被阅读0次

    json数据格式转换

    • 使用json_serializable库
    1. pubspec.yaml文件中添加依赖
    dependencies:
      json_annotation: ^4.4.0
    
    dev_dependencies:
      build_runner: ^2.1.4
      json_serializable: ^6.7.1
    
    1. 使用@JsonSerializable注解标记类
    import 'package:json_annotation/json_annotation.dart';
    
    import '../dio/HttpState.dart';
    part 'BaseResponse.g.dart';
    
    @JsonSerializable(genericArgumentFactories: true)
    class BaseResponse<T> {
      int status = 0;
      T? data;
      String? title;
    
      BaseResponse({
        required this.data,
        required this.status,
        required this.title,
      });
    
      bool isSuccess() {
        return status == HttpState.SUCCESS;
      }
    
      String getMessageAndCodeWithEmpty() {
        if (title == null) {
          return "";
        } else {
          return "${title!}:$status";
        }
      }
    
      factory BaseResponse.fromJson(
        Map<String, dynamic> json,
        T Function(dynamic json) fromJsonT,
      ) =>
          _$BaseResponseFromJson<T>(json, fromJsonT);
    
      Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
          _$BaseResponseToJson<T>(this, toJsonT);
    }
    
    1. 运行以下命令生成序列化文件
      flutter pub run build_runner build
    2. 导入生成一个名为xx.g.dart的文件
    3. 泛型处理
    part 'UserInfo.g.dart';
     @JsonSerializable(explicitToJson: true)
    class UserInfo {
      String? name;
      int age = 0;
      String? email;
    
      UserInfo({
        required this.name,
        required this.age,
        required this.email,
      });
    
      factory UserInfo.fromJson(Map<String, dynamic> json) =>
          _$UserInfoFromJson(json);
    
      Map<String, dynamic> toJson() => _$UserInfoToJson(this);
    }
    
    

    BaseResponse和UserInfo中的factory直接调用xx.g.dart文件

    测试

      void _checkJson(){
        String jsonString = '{"status":200,"data":{"name":"张三","age":18}}';
        Map<String,dynamic> jsonData = json.decode(jsonString);
        BaseResponse<UserInfo>? response = BaseResponse<UserInfo>.fromJson(jsonData, (json) => UserInfo.fromJson(json));
        Log.e("用户名称:${response.data?.name}");
      }
    
    

    相关文章

      网友评论

          本文标题:flutter入门到放弃5

          本文链接:https://www.haomeiwen.com/subject/ykfgwdtx.html