-
Notifications
You must be signed in to change notification settings - Fork 160
Description
$JsonSerializableConverter fails to parse List<DateTime> responses
Describe the bug
The generated $JsonSerializableConverter cannot handle API responses that return List<DateTime>. The converter has special handling for single DateTime responses, but when the response is List<DateTime>, it falls through to super.convertResponse() which uses cast<DateTime>() on the list of strings. This fails at runtime because strings cannot be cast to DateTime - they must be parsed using DateTime.parse().
To Reproduce
Swagger spec:
openapi: 3.0.0
paths:
/appointments/availability:
post:
responses:
'200':
description: Available appointment slots
content:
application/json:
schema:
type: array
items:
type: string
format: date-timeGenerated code produces a method with return type Future<Response<List<DateTime>>>.
When calling the endpoint and accessing response.body, you get:
type 'String' is not a subtype of type 'DateTime' in type cast
The issue is in the generated $JsonSerializableConverter:
class $JsonSerializableConverter extends chopper.JsonConverter {
@override
FutureOr<chopper.Response<ResultType>> convertResponse<ResultType, Item>(
chopper.Response response,
) async {
// ... handles empty body and String ...
// Handles single DateTime ✓
if (ResultType == DateTime) {
return response.copyWith(
body: DateTime.parse((response.body as String).replaceAll('"', '')) as ResultType,
);
}
// List<DateTime> falls through here and fails!
final jsonRes = await super.convertResponse(response);
return jsonRes.copyWith<ResultType>(
body: $jsonDecoder.decode<Item>(jsonRes.body) as ResultType,
);
}
}The parent JsonConverter.decodeJson() does body.cast<InnerType>() which creates a lazy cast wrapper that fails when accessed.
Expected behavior
response.body should return a properly parsed List<DateTime>:
// API returns: ["2026-01-10T10:00:00Z", "2026-01-10T11:00:00Z"]
// response.body should be: [DateTime(2026, 1, 10, 10, 0), DateTime(2026, 1, 10, 11, 0)]Swagger specification link
Any OpenAPI 3.0 spec with an endpoint returning array of string with format: date-time.
Library version used:
swagger_dart_code_generator: 3.0.1 (verified still broken in 4.1.1)chopper: 8.x- Dart SDK: 3.x
Additional context
Suggested fix - Add a check for Item == DateTime before calling super.convertResponse():
// Handle List<DateTime> specially since strings can't be cast to DateTime
if (Item == DateTime) {
final List<dynamic> jsonList = jsonDecode(response.bodyString);
final List<DateTime> dateTimeList =
jsonList.map((e) => DateTime.parse(e as String)).toList();
return response.copyWith<ResultType>(body: dateTimeList as ResultType);
}File to modify: lib/src/code_generators/swagger_additions_generator.dart - the generateCustomJsonConverter() method.
Workaround: Create a custom converter that extends JsonConverter with the fix above, and use it instead of the generated $JsonSerializableConverter.