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
相关推荐
coder_pig3 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
捡芝麻丢西瓜5 小时前
flutter自学笔记5- dart 编码规范
flutter·dart
恋猫de小郭5 小时前
什么?Flutter 可能会被 SwiftUI/ArkUI 化?全新的 Flutter Roadmap
flutter·ios·swiftui
nbsaas-boot7 小时前
探索 JSON 数据在关系型数据库中的应用:MySQL 与 SQL Server 的对比
数据库·mysql·json
疯一样的码农8 小时前
Jackson 的@JsonRawValue
json
Web打印11 小时前
web打印插件 HttpPrinter 使用半年评测
javascript·json·firefox·jquery·html5
手心里的白日梦13 小时前
网络计算器的实现:TCP、守护进程、Json、序列化与反序列化
网络·tcp/ip·json
chenchihwen13 小时前
数据分析时的json to excel 转换的好用小工具
数据分析·json·excel
子燕若水15 小时前
简要解释JSON Schema
前端·html·json
Json_1817901448016 小时前
淘系商品评论json数据示例参考,API接口系列
大数据·json·api