Flutter中HTTP POST请求时jsonEncode重复编码导致对象列表转为字符串的问题
解决Flutter中HTTP POST请求体列表被转成带转义字符串的问题
你遇到的问题核心是对timeSlots做了两次JSON编码,这才导致availableSlots变成了带转义字符的字符串。
问题分析
你先单独对timeSlots执行jsonEncode(timeSlots),得到了一个合法的JSON数组字符串;接着把这个字符串放进请求体的map中,再对整个map执行一次jsonEncode——这相当于把数组字符串当成普通文本再次编码,自然就会出现转义的引号和斜杠。
解决方案
直接把List<TimeSlot>对象放入请求体的map中,不需要单独编码。因为你的TimeSlot类已经实现了toJson()方法,外层的jsonEncode会自动递归处理列表里的每个对象,生成正确的JSON数组。
修改后的sendNewTutorship方法代码如下:
Future<Tutorship> sendNewTutorship( List<TimeSlot> timeSlots, String description, String tutorshipId, String courseId, String studentId) async { var body = jsonEncode({ 'tutorshipId': tutorshipId, 'studentId': studentId, 'courseId': courseId, 'availableSlots': timeSlots, // 直接传入List<TimeSlot>,不用提前编码 'description': description }); print(body); Map<String, String> headers = { 'Content-type': 'application/json', 'Accept': 'application/json', }; final response = await http.post( Uri.parse(Strings.serviceUrl + '/tutorships'), headers: headers, body: body, ); if (response.statusCode == 201) { return Tutorship.fromJson(jsonDecode(response.body)); } else { throw Exception('Could not create the tutorship'); } }
为什么这样有效?
Dart的jsonEncode函数会自动处理可序列化的对象:
- 对于
List类型,它会遍历列表中的每个元素 - 对于实现了
toJson()方法的自定义对象(比如你的TimeSlot),它会调用该方法将对象转为Map,再继续编码成JSON格式
这样最终生成的availableSlots字段就是标准的JSON数组,不会出现多余的转义字符。
内容的提问来源于stack exchange,提问作者Juan Camacho
相关产品推荐
相关产品推荐

