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
相关推荐
‘’林花谢了春红‘’6 小时前
C++ list (链表)容器
c++·链表·list
比格丽巴格丽抱9 小时前
flutter项目苹果编译运行打包上线
flutter·ios
SoaringHeart9 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
阿龟在奔跑9 小时前
引用类型的局部变量线程安全问题分析——以多线程对方法局部变量List类型对象实例的add、remove操作为例
java·jvm·安全·list
ashane131411 小时前
Java list
java·windows·list
djk888813 小时前
.net将List<实体1>的数据转到List<实体2>
数据结构·list·.net
AiFlutter13 小时前
Flutter通过 Coap发送组播
flutter
黎明晓月15 小时前
PostgreSQL提取JSON格式的数据(包含提取list指定索引数据)
postgresql·json·list
熬夜学编程的小王19 小时前
【C++篇】从基础到进阶:全面掌握C++ List容器的使用
开发语言·c++·list·双向链表·迭代器失效
心死翼未伤1 天前
python从入门到精通:pyspark实战分析
开发语言·数据结构·python·spark·json