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
相关推荐
张风捷特烈4 小时前
Flutter 伪3D绘制#03 | 轴测投影原理分析
android·flutter·canvas
owde7 小时前
顺序容器 -list双向链表
数据结构·c++·链表·list
第404块砖头7 小时前
分享宝藏之List转Markdown
数据结构·list
马拉萨的春天7 小时前
flutter 项目结构目录以及pubspec.ymal等文件描述
flutter
JeJe同学8 小时前
教程:如何使用 JSON 合并脚本
json·coco
ElasticPDF-新国产PDF编辑器14 小时前
React 项目 PDF 批注插件库在线版 API 示例教程
react.js·pdf·json
豆芽脚脚16 小时前
合并相同 patient_id 的 JSON 数据为数组
postgresql·json
还是鼠鼠1 天前
Node.js全局生效的中间件
javascript·vscode·中间件·node.js·json·express
bst@微胖子1 天前
Flutter项目之登录注册功能实现
开发语言·javascript·flutter
小墙程序员1 天前
Flutter 教程(十一)多语言支持
flutter