flutter 解析json另类封装方式 List<bean>,哈哈哈

flutter 解析json另类封装方式,哈哈哈

日常学习,仅供参考,不喜 勿喷

http请求数据泛型解析封装,需要判断泛型数据类型再根据类型解析,本文只抽取了list演示

核心代码

dart 复制代码
import 'dart:convert';

import 'package:webwsyn/http/bean/login_list.dart';
import 'package:webwsyn/http/bean/model.dart';

class ttzq {
  Future<List<T>> listPost<T>(
      String data, T Function(dynamic data) parseModel) async {
    try {
      final jsonMap = jsonDecode(data);
      print('接收数据:' + data);

      Model<List<dynamic>> response1 = Model<List<dynamic>>.fromJson(jsonMap);

      List<dynamic> list = response1.data as List;

      return list.map((e) => parseModel(e)).toList();
    } catch (e) {
      throw Exception('Failed to send POST request ${e}');
    }
  }

  Future<T> listPost2<T>(
      String data, T Function(dynamic data) parseModel) async {
    try {
      final jsonMap = jsonDecode(data);

      Model<dynamic> response1 = Model<dynamic>.fromJson(jsonMap);

      return parseModel(response1.data);
    } catch (e) {
      throw Exception('Failed to send POST request ${e}');
    }
  }

  Future<T> listPost3<T>(String data) async {
    try {
      final jsonMap = jsonDecode(data);

      Model<dynamic> response1 = Model<dynamic>.fromJson(jsonMap);

      return response1.data as T;
      //return parseModel(response1.data);
    } catch (e) {
      throw Exception('Failed to send POST request ${e}');
    }
  }
}

///测试方法
Future<int> main() async {
  /// List<T> ==========================================================================
  String jsonData =
      '{"code":200,"message":"操作成功","isboolean":true,"data":[{"id":1,"name":"admin","password":"123456"},{"id":2,"name":"admin","password":"123456"}]}';

  ttzq()
      .listPost<LoginList>(jsonData, (data) => LoginList.fromJson(data))
      .then((value) {

    //print(value[0].password);
     // 打印返回的数据

    value.forEach((element) {
      print(element.toJson());
    });
  });

  /// <T> ==========================================================================
  String jsonData2 = '{"code":200,"message":"操作成功","isboolean":true,"data":{"id":1,"name":"admin","password":"123456"}}';
  ttzq().listPost2(jsonData2,(data) => LoginList.fromJson(data)).then((value) {
    print('=============================');
    print(value.password);
  });

  /// <Sting>/<int>/<bool> ==========================================================================

  ///可以转换  数据类型 String int bool
  String jsonData3 =
      '{"code":200,"message":"操作成功","isboolean":true,"data":true}';

  ttzq().listPost3<bool>(jsonData3).then((value) {
    print("结果:${value}"  );
  });


  return 0;
}

//结构类

dart 复制代码
//json解析
import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class LoginList {
  late int id;

  late String name;

  late String password;

  LoginList.fromJson(Map<String, dynamic> json) {
    id = json['id'] as int;
    if (json.containsKey('name')) {
      name = json['name'] as String;
    }
    if (json.containsKey('password')) {
      password = json['password'] as String;
    }
  }

  Map<String, dynamic> toJson() =>
      {'id': id, 'name': name, 'password': password};

}
dart 复制代码
//json解析
import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class Model<T> {
  late bool isboolean;
  late int code;
  late T data;
  late String message;

  Model({
    required this.isboolean,
    required this.code,
    required this.data,
    required this.message,
  });

  Model.fromJson(Map<String, dynamic> json) {
    isboolean = json['isboolean'] as bool;
    code = json['code'] as int;
    if (json.containsKey('message')) {
      message = json['message'] as String;
    }
    if (json.containsKey('data')) {
      data = json['data'] as T;
    }
  }

  Map<String, dynamic> toJson() =>
      {'isboolean': isboolean, 'code': code, 'message': message, 'data': data};
}

导入架包

dart 复制代码
dependencies:
  flutter:
    sdk: flutter

  #json:
  json_annotation: ^4.8.0
相关推荐
肥肥呀呀呀7 小时前
flutter 高斯模糊闪烁问题
flutter
wilinz10 小时前
Flutter 图片压缩性能对比
flutter
程序员老刘1 天前
Dart MCP翻车了!3.9.0版本无法运行,这个坑你踩过吗?
flutter·ai编程·客户端
ideal树叶1 天前
flutter 中 的 关键字
flutter
世界不及妳微笑1 天前
Flutter 记录应用授权登录踩坑之旅
flutter
鹏多多2 天前
flutter-使用confetti制作炫酷纸屑爆炸粒子动画
android·前端·flutter
耳東陳12512 天前
【重磅发布】flutter_chen_updater-版本升级更新
flutter
HH思️️无邪2 天前
Flutter 开发技巧 AI 快速构建 json_annotation model 的提示词
flutter·json
笔沫拾光2 天前
hooks_riverpod框架解析
flutter·hooks·hooks_riverpod
problc2 天前
Flutter桌面应用实战:Windows系统代理切换工具开发
windows·flutter