草庐IT

flutter :- How to parse the JSON from the model class in flutter?

coder 2023-07-23 原文

我在 flutter 中像下面的代码一样从键和值中解析 JSON

 Future<LoginBean> login() async {
    var body = json.encode({"MOB": "1112223330", "KEY": "123456"});

    return http.post(
        Uri.encodeFull(
            "https://MY_Server/Users/login"),
        body: body.toString(),
        headers: {'Content-type': 'application/json'}).then((response) {
      print("Response Status : $response");

      if (response.statusCode == 200) {
         Map userMap = jsonDecode(json);
         var user = new LoginBean.fromJson(userMap);

         debugPrint("here is the response==>>>> $user");
      }
    });
  }

有没有其他方法像我们在 Android 中那样在 Model 类中解析 JSON,请查看下面的示例。

Gson gson = new Gson();

MY_LOGIN_BEAN loginBean = gson.fromJson(response, MY_LOGIN_BEAN.class);

我已经引用了这个链接但没有得到解决方案,请检查以下内容:-
1). Link
2). Link
3). Link

这是我的 JSON 响应

{"status":1,"message":"Login Successfully","data":{"userid":"101","Authorization":"eyJ1c2VyaWQiOiIxMDEiLCJ0b2tlbiI6IjVjYWRkYzUzMWY4YzAifQ==","roles":"2","firstname":"Ravindra","lastname":"kushwaha","fullname":"Ravindra kushwaha","wallet_amount":"845.00","mobile":"1112223330","email":"ravindra.kushwaha@consagous.com","chat_id":"","qrcode_image":"https:\/\/dapplepay.consagous.co.in\/uploads\/coupon_qr\/11C1f7ApJM8r.png","redirect_to_verify":"0","notification_status":"0","country_code":"91","Is_Allowed_Transaction":"1","profile_image":"https:\/\/dapplepay.consagous.co.in\/uploads\/user\/1553600479DapplePay1553600454461.png","fingerprint_status":"0"}}

我已经尝试了下面的代码行,请看一下,但我没有得到任何成功。

  class LoginBean {
  int status;
  String message;
  Data data;

  LoginBean({
    this.status,
    this.message,
    this.data,
  });


  static Map<String, dynamic> toMap(LoginBean loginBean){
    var map = Map<String, dynamic>();
    map['status'] = loginBean.status;
    map['message'] = loginBean.message;
    map['data'] = Data.toMap(loginBean);
    return map;
  }

  LoginBean.map(dynamic obj) {
    this.status = obj["status"];
    this.message = obj["message"];
    if (obj['data'] != null) {
      this.data = new Data.map(obj['data']);
    }
  }

  factory LoginBean.fromJson(dynamic json) {
    print('here we gooo');
    return LoginBean(
        status: json['status'],
        message: json['message'],
        data: new Data.fromJson(json['data'])
    );
  }

}

class Data {
  String userid;
  String authorization;
  String roles;
  String firstname;
  String lastname;
  String fullname;
  String walletAmount;
  String mobile;
  String email;
  String chatId;
  String qrcodeImage;
  String redirectToVerify;
  String notificationStatus;
  String countryCode;
  String isAllowedTransaction;
  String profileImage;
  String fingerprintStatus;


  Data.map(dynamic json) {
    this.userid = json['userid'];
    this.authorization = json['authorization'];
    this.roles = json['roles'];
    this.firstname = json['firstname'];
    this.lastname = json['lastname'];
    this.fullname = json['fullname'];
    this.walletAmount = json['walletAmount'];
    this.mobile = json['mobile'];
    this.email = json['email'];
    this.chatId = json['chatId'];
    this.qrcodeImage = json['qrcodeImage'];
    this.redirectToVerify = json['redirectToVerify'];
    this.notificationStatus = json['notificationStatus'];
    this.countryCode= json['countryCode'];
    this.isAllowedTransaction = json['isAllowedTransaction'];
    this.profileImage = json['profileImage'];
    this.fingerprintStatus = json['fingerprintStatus'];
  }


  static Map<String, dynamic> toMap(LoginBean loginBean){
    var map = Map<String, dynamic>();
    map['userid'] = loginBean.data.userid;
    map['authorization'] = loginBean.data.authorization;
    map['roles'] = loginBean.data.roles;
    map['firstname'] = loginBean.data.firstname;
    map['lastname'] = loginBean.data.lastname;
    map['fullname'] = loginBean.data.fullname;
    map['walletAmount'] = loginBean.data.walletAmount;
    map['mobile'] = loginBean.data.mobile;
    map['email'] = loginBean.data.email;
    map['chatId'] = loginBean.data.chatId;
    map['qrcodeImage'] = loginBean.data.qrcodeImage;
    map['redirectToVerify'] = loginBean.data.redirectToVerify;
    map['notificationStatus'] = loginBean.data.notificationStatus;
    map['countryCode'] = loginBean.data.countryCode;
    map['isAllowedTransaction'] = loginBean.data.isAllowedTransaction;
    map['profileImage'] = loginBean.data.profileImage;
    map['fingerprintStatus'] = loginBean.data.fingerprintStatus;
    return map;
  }

  factory Data.fromJson(dynamic json) {
    return Data(
      userid: json['userid'],
      authorization: json['authorization'],
      roles: json['roles'],
      firstname: json['firstname'],
      lastname: json['lastname'],
      fullname: json['fullname'],
      walletAmount: json['walletAmount'],
      mobile: json['mobile'],
      email: json['email'],
      chatId: json['chatId'],
      qrcodeImage: json['qrcodeImage'],
      redirectToVerify: json['redirectToVerify'],
      notificationStatus: json['notificationStatus'],
      countryCode: json['countryCode'],
      isAllowedTransaction: json['isAllowedTransaction'],
      profileImage: json['profileImage'],
      fingerprintStatus: json['fingerprintStatus'],

    );
  }

  Data({
    this.userid,
    this.authorization,
    this.roles,
    this.firstname,
    this.lastname,
    this.fullname,
    this.walletAmount,
    this.mobile,
    this.email,
    this.chatId,
    this.qrcodeImage,
    this.redirectToVerify,
    this.notificationStatus,
    this.countryCode,
    this.isAllowedTransaction,
    this.profileImage,
    this.fingerprintStatus,
  });
}

当我使用模型类解析 JSON 时,我从上面的代码中得到以下异常

2019-04-10 18:59:28.553 11121-11153/democom.first_flutter_app E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
    #0      _LoginScreen.login.<anonymous closure> (package:first_flutter_app/onBording/login_screen.dart:139:34)
    #1      _rootRunUnary (dart:async/zone.dart:1132:38)
    #2      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
    #3      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
    #4      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
    #5      Future._propagateToListeners (dart:async/future_impl.dart:668:32)
    #6      Future._complete (dart:async/future_impl.dart:473:7)
    #7      _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
    #8      _AsyncAwaitCompleter.complete (dart:async/runtime/libasync_patch.dart:28:18)
    #9      _completeOnAsyncReturn (dart:async/runtime/libasync_patch.dart:294:13)
    #10     _withClient (package:http/http.dart)
    <asynchronous suspension>
    #11     post (package:http/http.dart:70:3)
    #12     _LoginScreen.login (package:first_flutter_app/onBording/login_screen.dart:129:12)
    <asynchronous suspension>
    #13     _LoginScreen.build.<anonymous closure>.<anonymous closure> (package:first_flutter_app/onBording/login_screen.dart:102:25)
    #14     _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
    #15     _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:568:30)
    #16     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:120:24)
    #17     TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
    #18     TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
    #19     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:369:9)
    #20     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
    #21     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
    #22     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:214:19)
    #23     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22)
    #24     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7)
    #25     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
    #26     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
    #27     _rootRunUnary (dart:async/zone.dart:1136:13)
    #28     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
    #29     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
    #30     _invoke1 (dart:ui/hooks.dart:223:10)
    #31     _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)

最佳答案

你正在解码 json,而你应该像这样解码响应中收到的正文 -

var userMap = jsonDecode(response?.body);

关于 flutter :- How to parse the JSON from the model class in flutter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55612365/

有关flutter :- How to parse the JSON from the model class in flutter?的更多相关文章

  1. Flutter 环境变量配置和flutter doctor中的错误解决 - 2

    一、环境变量右键点击我的电脑-属性:然后找到环境变量 1.Android的SDK不在C盘的话需要额外配这个到用户环境变量:ANDROID_HOMED:\AndroidSDK2.然后在系统变量:Path中添加一条这样的值        D:\Flutter\flutter\bin             这个值写flutter包解压的实际地址即可 3.在系统变量中添加两个镜像变量:        变量名:FLUTTER_STORAGE_BASE_URL      变量值:https://storage.flutter-io.cn        变量名:PUB_HOSTED_URL      变量

  2. flutter 中最详细的继承,多态,接口讲解 - 2

    flutter中最详细的继承,多态,接口讲解前言一、继承(Extends)二、混合mixins(with)2.1、最简单的mixin2.2、on关键字,基于某个类型的mixin2.3、多个mixin2.4、mixin怎么实现多继承三、接口的实现(implement)总结前言众所周知,dart是一门单继承的语言,但是我们在日常开发中,会遇到各种各样的问题,比如,我们需要在dart中实现多继承,那么改怎么办呢?本篇文章,我将和大家聊聊关于dart中的继承,接口,混合的相关知识。类型解决什么问题使用场景限制extends子类继承子类继承父类只能继承一个父类,会继承父类的可见的属性和方法,不能继承构造

  3. Flutter实现文件上传华为对象存储(OBS) - 2

      本文主要讲述在Flutter项目中如何实现将文件上传到华为OBS(对象存储)中,并封装为三方库方便灵活使用。背景介绍  在大多项目中都会存在文件上传的需求,之前的实现都是调用后台的文件上传接口将文件上传到服务器上,但是这样会存在一个问题,因为文件上传会占用带宽导致在文件上传中调用其他接口的时候就会存在访问慢的情况,解决方案当然是升级带宽或者单独使用一台服务器作为文件服务,而且要带宽足够大不然上传下载的时候会很慢,但是这样两种方案成本都比较高。随着云计算的到来,各大云服务商都提供了对象存储的服务,费用便宜、带宽高、不影响业务系统而且提供了很多附加功能,比如图片处理、图片鉴黄等功能。  因目前

  4. Flutter项目 - 2

    一、项目简介本节的学习目标是通过Flutter技术,实现仿拉勾教育App的效果。其主要的UI效果如下:二、初始化项目初始化项目fluttercreateflutter_project修改文件flutter项目/android/build.gradle,把google()和jcenter()这两行去掉。改为阿里的镜像地址。//google()//jcenter()maven{url'https://maven.aliyun.com/repository/google'}maven{url'https://maven.aliyun.com/repository/jcenter'}maven{url

  5. 在 Flutter 中使用 webview_flutter 4.0 | 基础用法与事件处理 - 2

    大家好,我是17。FlutterWebView一共写了四篇文章在Flutter中使用webview_flutter4.0|js交互FlutterWebView性能优化,让h5像原生页面一样优秀,已入选掘金一周2023.02.22期FlutterWebView如何与h5同步登录状态已入选CSDN每天值得看–2023-02-21在Flutter中使用webview_flutter4.0|基础用法与事件处理本文是第4篇,定位是新手入门,介绍和演示webview的基础用法。最后还介绍了事件处理的技巧。因为是补写的,所以本来应该首发的却发在最后了。环境准备已经在在Flutter中使用webview_fl

  6. 在flutter中使用NFC(超全) - 2

    文章前景:目前公司主要的业务方向是sass平台,我们的admin系统是基于qiankun搭建的主基座和子模块,app是flutter+h5。我主要负责的是1、qiankun基座的搭建2、flutter基座和通信jsbridge的搭建3、app内h5的书写4、模块开发规范的书写5、…在完善通信jsbridge时,发现有模块需要是需要基于nfc实现的,所以我需要完善ios与android的nfc功能在pub上看到nfc_manager反馈还不错,调查了一下,基本需求可以达到。在此,总结一下几个关键点,希望可以帮助到更多的小伙伴。一、加入插件首先,我们需要在yaml文件加入该pubdependenc

  7. Flutter局部刷新解决闪烁问题 - 2

    在开发Flutter倒计时,setState刷新会造成页面的闪烁,如图一、setState全局刷新1、setState页面问题分析在flutter中常用的刷新方法有setState,然后这个会造成整个页面刷新,特别是绘制需要时间的组件会闪烁.2、setState页面源码login_demo_page.dartimport'dart:async';import'dart:collection';import'dart:convert';import'package:flutter/material.dart';classLoginDemoPageextendsStatefulWidget{Log

  8. Android集成高德Flutter地图(三)定位 - 2

    一、集成高德地图我的项目是需要显示地图的,所以定位是在地图的基础上实现的,当然定位也可以单独实现,获取到位置相关各种信息二、集成高德定位①、集成定位基础SDK在Flutter项目中Android文件夹下的build.gradle添加implementation('com.amap.api:location:6.1.0')注意兼容性处理我这里集成的是Flutter3.0插件所以配置build.gradle为:dependencies{//高德地图Flutter插件内不包含基础SDK包,使用时请参考官网关于集成Android地图SDK和iOS地图SDK说明配置地图SDK//高德地图Flutter插

  9. Flutter高仿微信-项目实践59篇 - 2

    Flutter高仿微信(支持Android和IOS系统)Flutter高仿微信主要包含5大模块:1、Web服务器2、Flutter客户端3、Xmpp即时通讯服务器4、视频通话服务器5、腾讯云服务器另外也有Kotlin版本高仿微信功能,Kotlin版本跟Flutter同时开发,调用的是同一个服务器接口。Flutter高仿微信目录Flutter高仿微信-第1篇-注册Flutter高仿微信-第2篇-登录Flutter高仿微信-第3篇-主页Flutter高仿微信-第4篇-主页-消息Flutter高仿微信-第5篇-主页-通讯录Flutter高仿微信-第6篇-主页-我的Flutter高仿微信-第7篇-个人

  10. 22、 Flutter Widgets 之 NestedScrollView 组件。 - 2

    Flutter中常用的滑动布局ScrollView有SingleChildScrollView、NestedScrollView、CustomScrollView。SingleChildScrollView用来处理简单可滑动的页面布局视图,如一般的数据详情页面,当内容足够多时,一屏显示不下时,就需要滑动处理。NestedScrollView滑动组件是用来处理复杂情况下的滑动应用场景,如向上滑动视图时,要折叠隐藏一部分内容,这时候就需要使用到NestedScrollView与SliverAppBar的结合使用。CustomScrollView用来处理更为复杂的布局结合SliverAppBar,S

随机推荐