flutter - FormatException:意外字符(在字符 1 处),这是我在解码我的 json 格式时发生的错误
问题描述
我正在尝试使用 http 包发布和获取数据。我在 onPressedEvent 中有一个函数
onPressed: () {
getAttendance();
},
这是触发 getAttendanceStatus() 方法的函数。
void getAttendance() async {
List returnedData = await getAttendanceStatus(context);
print(returnedData);
}
问题在于 getAttendanceStatus() 方法......
Future<List> getAttendanceStatus(BuildContext context) async {
List decodedData;
final _url = 'https://abcd.000webhostapp.com/abcd.php';
try {
final response = await http.post(_url, body: {
'dept': 'Computer',
'year': '4',
'sem': 'even',
'sec': 'A',
'day': 'monday',
'roll_number': '1807025',
});
if (response.statusCode == 200) {
var data = response.body;
decodedData = jsonDecode(data);
print('decodedData: $decodedData');
} else {
print(response.statusCode);
}
} catch (e) {
print('Catch: $e');
}
return decodedData;
}
这是我从互联网上获取的实际数据。这不过是 response.body
[{"monday":"EBS","course_code":"UCEC039","1807025":"0","date":"Jan 26"},{"monday":"ITP II","course_code":"UCEC047","1807025":"0","date":"Jan 26"}]
这是错误:
I/flutter (24940): Catch:: FormatException: Unexpected character (at character 1)
I/flutter (24940): Array
I/flutter (24940): ^
I/flutter (24940): null
解决方案
我很确定您需要将字符串而不是数组传递给 body 字段。所以只需像这样对你的身体进行 jsonEncode 编码:
try {
final response = await http.post(_url, body:
jsonEncode({
'dept': 'Computer',
'year': '4',
'sem': 'even',
'sec': 'A',
'day': 'monday',
'roll_number': '1807025',
},
),
);
此外,您可能希望为您的请求添加超时,并且如上所述,您还需要用 try/catch 包围您的 jsonDecode,以防响应不是有效的 json。
推荐阅读
- python - 我的 Etherscan API 脚本在完美运行 3 天后停止工作,并简单地打印“Killed”作为其最终消息,为什么?
- android - Android FirebaseUI 登录时出现 Google 错误以获取发布密钥
- python - 在 python 中使用 smtp 类发送自动电子邮件
- database - 有条件地从 postgres 中的数据库中删除重复项
- c - 在任何给定平台上,C 中的哪些类型大小将保持不变?
- php - 根据字符串的一部分对 foreach 结果进行排序 - PHP
- javascript - 是否有快速方法/快捷方式来扩展 VS 代码括号中的内容(不折叠/扩展方法)
- delphi - Firebird / DELPHI - 不支持嵌套事务
- python - 如何从数据流中的谷歌存储桶中读取 csv 文件,组合,对数据流中的数据帧进行一些转换,然后将其转储到 bigquery 中?
- python - 如何从机器人向另一个用户发送消息