首页 > 解决方案 > 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

标签: flutterhttpdart

解决方案


我很确定您需要将字符串而不是数组传递给 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。


推荐阅读