首页 > 解决方案 > 如何访问从 Flutter 中的 HTTP POST 请求获得的 JSON 响应?

问题描述

我有一个登录页面,我发出一个 HTTP POST 请求以在 API 中发布用户的数据,然后我得到一个我想要访问并保存到我的应用程序中的响应。这是我的代码:

这是 JSON 响应:


{
    "code": 200,
    "status": "succes",
    "message": "You are now logged in",
    "name": "Robert Doctor",
    "phone": "0756374360",
    "role": "doctor",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI",
    "connCode": 233121
}

标签: jsonflutterdart

解决方案


它们有几种方法,如果您有很多方法要做,您可能想看看其他方法,但一个简单的手动方法是:

import 'dart:convert';

// response being the response object you got back from your http call
var payload = MyResponse.fromJson(json.decode(response.body))

class MyResponse {
  final String message;
  final String name;
  final String phone;
  // etc ....

  MyResponse(this.message, this.name, this.phone);

  MyResponse.fromJson(Map<String, dynamic> json)
      : message = json['message'],
        name = json['name'],
        phone = json['phone'];
}

推荐阅读