【问题标题】:How to get json response in flutter using POST method?如何使用 POST 方法在颤振中获得 json 响应?
【发布时间】:2021-08-09 12:26:20
【问题描述】:

我是 Flutter 的初学者。请帮助我在颤振中获取并将下面的 json 数据设置为模型。我正在使用 POST 方法。 '''

{
"success": 1,
"data": {
    "user_id": 2,
    "email": "ajay.singhal@ollosoft1.com",
    "phone": "9414905280",
    "password": "1436a615e62482ba4f075c1d4a4fd94b",
    "account_status": "Active",
    "date_of_birth": "1953-09-07T00:00:00.000Z",
    "address": "Jaipur Rajasthan",
    "profile_url": "http://18.217.236.99:4200/assets/profile_img/2/RBI-keeps-policy-rate-unchanged-1.jpg",
    "first_name": "Ajay",
    "last_name": "singhal"
}

}

'''

下面是我的 Model 类,名为 UserInfoModel

      import 'UserInfoDataModel.dart';
  
  class UserInfoModel {
    final int success;
    final UserInfoDataModel data;
  
    UserInfoModel(this.success, this.data);
  
    factory UserInfoModel.fromJson(dynamic json) {
      if (json['data'] != null) {
        var tagObjsJson = json['data'];
        UserInfoDataModel _tags =
            tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
  
        return UserInfoModel(json['success'] as int, _tags);
      }
    }
  
    @override
    String toString() {
      return '{${this.success}, ${this.data}}';
    }
  }

下面是子模型名称是 UserInfoDataModel

        import 'package:flutter/material.dart';
    
    class UserInfoDataModel {
      int user_id;
      String email;
      String phone;
      String password;
      String account_status;
      String date_of_birth;
      String address;
      String profile_url;
      String first_name;
      String last_name;
    
      UserInfoDataModel(
          {this.user_id,
          this.email,
          this.phone,
          this.password,
          this.account_status,
          this.date_of_birth,
          this.address,
          this.profile_url,
          this.first_name,
          this.last_name});
    
      factory UserInfoDataModel.fromJson(Map<String, dynamic> json) {
        return UserInfoDataModel(
          user_id: json['user_id'] as int,
          email: json['email'],
          phone: json['phone'],
          password: json['password'],
          account_status: json['account_status'],
          date_of_birth: json['date_of_birth'],
          address: json['address'],
          profile_url: json['profile_url'],
          first_name: json['first_name'],
          last_name: json['last_name'],
        );
      }
    }

我的 APi 调用在下面使用 POST 方法 我已成功获得响应,但无法在模型中设置

         UserInfoModel _userInfoModel;
      UserInfoDataModel _userInfoDataModel;
    
      String url = BaseURLHeaders().getBaseURl() + "userInfo";
      Map headers = BaseURLHeaders().getHeader();
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        getData();
      }
    
      Future<UserInfoModel> getData() async {
        String user_id = "1";
        var mapData = new Map<String, dynamic>();
        mapData['user_id'] = user_id;
        // mapData['first_name'] = firstName;
    
        var response = await http.post(
          url,
          headers: headers,
          body: mapData,
        );
        setState(() {
          print("userInfoDetails: ${response.body}");
          print("urlTop: ${url}");
          print("headersTop: ${headers}");
          print("responseCode: ${response.statusCode}");
        });
    
        if (response.statusCode == 200) {
          var res = json.decode(response.body);
          _userInfoModel = UserInfoModel.fromJson(res);
          if (_userInfoModel.success == 1) {
            var data = res["data"];
    
            setState(() {
              print("responseBody: ${res}");
              print("userInfoSuccess: ${_userInfoModel.success}");
              print("dataVaalue: ${data["email"]}");
              print("urlBelow: ${url}");
              print("headersBelow: ${headers}");
            });
          }
        }
      }

【问题讨论】:

  • 请添加您尝试过的内容以及需要帮助的地方。
  • @NidheeshMT 请查看我上面更新的代码

标签: json flutter dart post


【解决方案1】:

你可以在颤振中使用json_serializer。见flutter docs。 如果你使用 IntelliJ IDEA,你可以使用DartToJson 包。它会自动为您生成,您可以使用fromJsontoJson 方法。

【讨论】:

    【解决方案2】:
     UserInfoDataModel _tags =
                tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
    

    这里实际上将 tagObjsJson 视为一个列表。但它是一个 JsonObject,所以你不需要 map 函数。

    你可以访问对象

    UserInfoDataModel _tags =UserInfoDataModel.fromJson(tagJson);
    

    【讨论】:

    • 非常感谢@Nidheesh MT,它现在可以工作了。你真是个好人,非常感谢你的朋友。
    猜你喜欢
    • 2021-04-12
    • 2017-09-18
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    相关资源
    最近更新 更多