json - 如何访问从 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
}
解决方案
它们有几种方法,如果您有很多方法要做,您可能想看看其他方法,但一个简单的手动方法是:
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'];
}
推荐阅读
- php - 消息:试图在 php 错误中获取非对象的属性
- .htaccess - 如果没有字符串,则重定向 url
- maven - Maven 将源文件复制到一个文件夹
- javascript - 为什么 'class' 必须是 JavaScript 中的保留关键字?
- git - 如何将文件夹放到不同的分支?
- android - Android Log.d 打印行号
- node.js - UnhandledPromiseRejectionWarning:错误:在选择器“小部件”处修剪来自:Ionic
- php - Codeigniter 计数注册访客
- installation - ubuntu 18.04上安装opennebula的问题
- python - Multiprocessing.Pool.Map 不做任何事情