Json.Encode() 不识别对象,将它们设置为字符串 FLUTTER

Json.Encode() Doesnt Recognize objects, sets them as a string FLUTTER

我正在尝试向我的应用程序后端发送 HTTP post 请求,问题是当我将请求的主体设置为字符串时。目前我正在使用 class TimeSlot。

class TimeSlot {
final String id;
final int year;
final int month;
final int day;
final int hour;

TimeSlot(
  {this.year = 0,
  this.day = 0,
  this.hour = 0,
  this.month = 0,
  required this.id});

Map toJson() => {'year': year, 'month': month, 'day': day, 'hour': hour};
}

和方法

Future<Tutorship> sendNewTutorship(
  List<TimeSlot> timeSlots,
  String description,
  String tutorshipId,
  String courseId,
  String studentId) async {
var slots = jsonEncode(timeSlots);

var body = jsonEncode({
  'tutorshipId': tutorshipId,
  'studentId': studentId,
  'courseId': courseId,
  'availableSlots': slots,
  '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');
} 
}

print 方法向我展示了如何解析 TimeSlot 列表,这正是我想要的: [{"年":2021,"月":8,"日":8,"小时":9}]

但是当设置到正文请求中时,它会变成这样的字符串:

[{\"年\":2021,\"月\":8,\"日\":11,\"小时\":9}]"

有什么方法可以避免这种行为?

您对时隙进行了两次编码,并且没有将时隙转换为地图列表,因此请更改

var slots = jsonEncode(timeSlots);

var body = jsonEncode({
  'tutorshipId': tutorshipId,
  'studentId': studentId,
  'courseId': courseId,
  'availableSlots': slots,
  'description': description
});

至此

(也更喜欢 final 关键字来定义不可变变量)

final body = jsonEncode({
  'tutorshipId': tutorshipId,
  'studentId': studentId,
  'courseId': courseId,
  'availableSlots': timeSlots.map((x) => x.toMap()).toList(),
  'description': description
});

关于Json的解释:

  • Json 编码意味着将映射或列表转换为字符串,我们将此字符串命名为 Json
  • Json 解码意味着将 Json(字符串)转换为编码前的状态